초기화 선언을 간단하게 하는 방법
auto 변수는 type이 초기치부터 연역되기 때문에 반드시 초기치를 제공해야 한다.
그래서 변수의 초기화를 빼먹는 실수를 할 여지가 없어진다.
int x1; // 문맥에 따라 초기화되지 않을 수 있다.
auto x2; // error
auto x3 = 0;
auto는 type deduction을 사용하기 때문에 컴파일러만 알던 형식을 지정할 수 있다.
template<typename It>
void dwim(It b, It e)
{
for(; b!=e; ++b){
//typename std::iterator_traits<It>::value_type
// currValue = *b;
auto currValue = *b;
}
}
C++14 에서는 람다 표현식의 매개변수에도 auto를 적용할 수 있게 되었다.
//auto derefUPLess =
// [](const std::unique_ptr<Widget>& p1,
// const std::unique_ptr<Widget>& p2)
// { return *p1<*p2; }
auto derefUPLess =
[](const auto& p1,
const auto& p2)
{ return *p1<*p2; }
std::function 과 비교
std::function< bool(const std::unique_ptr<Widget>&,
const std::unique_ptr<Widget>&)>
derefUPLess = [](const std::unique_ptr<Widget>& p1,
const std::unique_ptr<Widget>& p2)
{ return *p1 < *p2; };
auto를 이용하는 경우 클로저와 같은 형식이며 클로저에 요구되는 만큼의 메모리만 사용한다.
std::function은 템플릿 인스턴스이며 auto 보다 메모리를 더 많이 소비한다.
또한, auto로 선언된 객체를 통해 호출하는 것보다 느리다.
type shortcut 관련 문제 회피
std::vector<int> v;
unsigned sz = v.size();
v.size() 의 공식적인 반환 형식은 std::vector<int>::size_type 이다.
이는 부호없는 정수 형식으로 지정되기 때문에 많은 프로그래머들이 unsigned 로 충분하다고 생각한다.
64bit Windows 환경에서는 unisigned 는 32 비트인 반면, std::vector<int>::size_type 은 64 비트이다.
즉, 32 비트 Windows 에서 잘 동작하는 코드가 64비트 Windows 에서는 오작동할 수 있음을 의미한다.
auto sz = v.size() // sz 형식 : std::vector<int>::size_type
해시 테이블 예제
std::unordered_map<std::string, int> m;
for(const std::pair<std::string, int>& p : m)
{
// p 로 먼가를 수행
}
std::unordered_map 의 key 부분이 const이기 때문에 해시 테이블에 담긴 std::pair 의 형식은 std::pair<const std::string, int> 가 되어야 한다.
컴파일러는 루프 위의 p에 대해 선된 형식과 다르기 때문에 std::pair<const std::string, int> -> std::pair<std::string, int> 객체들로 변환하려고 하는 동작이 반복된다.
for (const auto& p : m)
{
...
}
명시적으로 타입을 선언하면서 기대하지 않은 암시적 변환이 발생할 수 있음을 보여준다.
'Effective Modern C++' 카테고리의 다른 글
EMC++ item 7 : Distinguish between () and {} when creating objects. (0) | 2022.08.28 |
---|---|
EMC++ item 6 : Use the explicitly typed initializer idiom when auto deduces undesired types. (0) | 2022.08.28 |
EMC++ item 4 : 연역된 형식을 파악하는 방법을 알아두라 (0) | 2022.08.15 |
EMC++ item 3 : decltype의 작동 방식을 숙지하라 (0) | 2022.08.15 |
EMC++ item 2 : auto의 type deduction을 숙지하라 (0) | 2022.08.15 |
댓글