균일된 초기화 방식 (Uniform Initialization)
어떤 상황이든 변수를 초기화 할 때, 중괄호 초기화를 사용할 수 있음을 보장한다.
즉, 일관성 있게 중괄호 초기화을 모든 상황에 적용할 수 있다.
- 일반변수 초기화 (vairable)
- 멤버변수 초기화 (member variable)
- 상수변수 초기화 (const vairable)
- 정적변수 초기화 (static variable)
- 참조변수 초기화 (reference variable)
- 구조체 초기화 (implicitly initialize objects)
- 암묵적 함수 인자값 초기화 (implicitly initailize function parameter)
- 암묵적 함수 리턴값 초기화 (implicitly initailize objects to return)
균일된 초기화가 가능한 이유는, 이전 장에서 소개했던 2가지의 기능 덕분이다.
균일된 초기화를 사용하면, 컴파일러는 아래의 기능 중 하나를 유동적으로 선택한다.
단, 위 2가지 기능은 문법이 같으므로 서로 혼합하여 사용했을 때 모호성이 존재한다.
혼용하여 사용했을 때, gcc는 initailizer_list 생성자를 우선적으로 호출하지만,
다른 컴파일러는 다르게 동작할 수 있다.
컴파일러마다 전략이 다르므로 주의하자.
즉, 균일된 초기화 방식을 도입할 때에는
사용하고 있는 컴파일러가 어떤 전략을 사용하는지 테스트가 필요하다.
적용 사례
거의 모든 경우에서 중괄호 초기화를 사용할 수 있다.
- 변수 초기화 (원시, 참조, 상수, 정적)
int i {3}; // or = {3};
int& lvalue_ref_i {i};
int&& rvalue_ref_i {3};
const int const_i {3};
static int static_i {3};
멤버변수 초기화
class data {
public:
int a;
data(): a{0} // aggregate init.
{
// do something.
};
};
생성자 초기화 (By Aggregate init, Call Constructor)
class data {
public:
int a;
int b;
data(int _a, int _b){
a = _a;
b = _b;
}
};
data data1{0, 0};
std::pair<int, string> pair1{0, "Hello, World!"};
구조체 초기화 (By Aggregate init)
class data {
public:
int a;
int b;
};
data data1{0, 0};
구조체 초기화 (By Initializer_list)
template <typename T>
class data {
public:
T* array;
data(initializer_list<T> list){
array = new T[list.size()];
unsigned long idx = 0;
for(T var : list){
array[idx] = var;
idx++;
}
}
};
data<int> data1{0, 0};
std::vector<int> vector1{1, 2, 3, 4};
배열 초기화
int fixed_array[10] {1, 2, 3};
int undetermined_array[] {1, 2, 3};
암묵적 함수 인자값 초기화
class data{
public:
int a;
int b;
};
void foo(data _data){};
foo({1, 2});
암묵적 함수 리턴값 초기화
class data{
public:
int a;
int b;
data clone(){
return {a, b};
}
};
참고 문헌
'# Lang > C++' 카테고리의 다른 글
| 6.3 이니셜라이져 리스트 (0) | 2019.05.04 |
|---|---|
| 6.2 중괄호 리스트 초기화 (0) | 2019.04.30 |
| 6.1 로컬변수 초기화 (0) | 2019.04.22 |
| 5.2 완벽한 전달 (0) | 2019.04.19 |
| 5.1 이동 의미론 (0) | 2019.04.18 |