* 본 내용은 C++의 Tips of Week를 번역하였습니다.
1. 초기화
=> C++11부터는 다양한 초기화 스타일을 제공함
=> {}를 사용하는 방법도 있고 직접초기화를 사용하는 방법도 존재하지만, 직관적이지 않은 경우가 많음
2. "=" vs "{}"
=> 의도된 리터럴 값으로 직접 초기화 할때 할당 구문을 스마트포인터와 함께 사용할 수 있으며, vector등의 구조 초기화를 수행 가능
// Good Code
int x = 2;
std::string foo = "Hello World";
std::vector<int> v = {1, 2, 3};
std::unique_ptr<Matrix> matrix = NewMatrix(rows, cols);
MyStruct x = {true, 5.0};
MyProto copied_proto = original_proto;
// Bad Code
int x{2};
std::string foo{"Hello World"};
std::vector<int> v{1, 2, 3};
std::unique_ptr<Matrix> matrix{NewMatrix(rows, cols)};
MyStruct x{true, 5.0};
MyProto copied_proto{original_proto};
3. "()" vs "{}"
=> 초기화가 단순히 값을 함께 구성하는것이 아닌 일부 활성 논리(active logic)을 수행할 때는 괄호 포함의 생성자 구문 사용
// Good code
Frobber frobber(size, &bazzer_to_duplicate);
std::vector<double> fifty_pies(50, 3.14);
// Bad code
Frobber frobber{size, &bazzer_to_duplicate};
std::vector<double> fifty_pies{50, 3.14};
4. "{}"를 사용하는 경우
=> 위의 옵션들이 컴파일 되지 않는 경우에만 = 없이 {}초기화 사용
class Foo {
public:
Foo(int a, int b, int c) : array_{a, b, c} {}
private:
int array_[5];
// 생성자가 명시적 표시가 되었으므로 {}사용
// 복사불가
EventManager em{EventManager::Options()};
};
5. {} + auto
=> auto와 {}는 같이 사용해서는 안됨
=> 직접초기화보다는 복사 초기화를 선호해야 하고, 직접초기화에 의존할 경우 {}보다는 ()사용
// Bad code
auto x{1};
auto y = {2}; // This is a std::initializer_list<int>!
6. 본문
abseil / Tip of the Week #88: Initialization: =, (), and {}
An open-source collection of core C++ library code
abseil.io
'C++ > Tips' 카테고리의 다른 글
[C++] Compilation Process (0) | 2021.06.25 |
---|---|
[C++] Try / Catch _2 (0) | 2021.06.24 |
[C++] Predefined Macro (0) | 2021.06.23 |
[C++] 가변인자[variable argument] (0) | 2021.06.22 |
[C++] New_2 (0) | 2021.06.21 |