프로그래밍/Modern c++
{ } 중괄호 초기화
오늘의논리
2023. 3. 6. 22:16
728x90
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
class Knight
{
public:
Knight()
{
}
Knight(initializer_list<int> li)
{
cout << "Knight(initializer_list)" << endl;
}
};
int main()
{
int a = 0;
int b(0);
int c{ 0 };
Knight k1;
Knight k2 = k1; // 복사 생성자(대입연산자 X)
Knight k3{ k2 };
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
vector<int> v2(10, 1);
//중괄호 초기화
//1. vector 등 container와 잘 어울린다
vector<int> v3{ 1,2,3,4 };
//2. 축소 변환 방지
int x = 0;
//double y{ x }; // 축소 변환을 허가하지 않아 에러가 남
//3. 보너스
Knight k4{};
//4. 단점 : initializer_list 버전 생성자가 필요(클래스)
//initializer_list 버전 생성자가 생길경우 다른 생성자를 대부분 무시
Knight k5{1, 2, 3,4,5};
return 0;
}
*괄호 초기화 ()를 기본으로 간다면?
- 전통적인 C++(거부감이 없음)
- vector 등 특이한 케이스에 대해서만 {} 사용
중괄호 초기화{}를 기본으로간다면?
- 초기화 문법의 일치화
- 축소 변환 방지
728x90