Brace Initialization¶
Brace Initialization: Motivation (1)¶
Initialization was always inconsistent ⟶ Extremely confusing, especially for newbies!
Integral types
Aggregates (struct, array)
Class objects
Container (e.g.
std::vector
) initialization with contained values ⟶push_back()
orgies
Brace Initialization: Motivation (2)¶
Integral Types
|
Integer Initialization int x = 7; // assignment style
int y(42); // ctor style
|
Brace Initialization: Motivation (3)¶
Aggregates
|
Aggregate Initialization int arr[] = {1, 2, 3};
struct s { int i,j; }
s s1 = {1, 2};
s s2 = {1}; // s2.j==0
|
Brace Initialization: Motivation (4)¶
Objects
|
Object Initialization class C {
public:
C(int i, int j);
};
C c1(1,2);
C c2 = c1;
|
Brace Initialization: Motivation (5)¶
Containers
|
Container Initialization int arr[] = {1,2,3};
vector<int> v1(arr, arr+3);
vector<int> v2(v1.cbegin(), v1.cend());
set<int> s;
s.insert(1);
s.insert(2);
vector<int> v(s.cbegin(), s.cend());
|
Brace Initialization: Motivation (6)¶
Member Arrays
|
Member Array Initialization class C {
public:
C() : data_(/*dammit!*/) {}
private:
const int data_[3];
};
|
Brace Initialization: Motivation (7)¶
Arrays on the Heap
|
Heap Array Initialization const int *arr = new int[42];
// and now?
|
Brace Initialization: Solution (1)¶
Solution: brace initialization everywhere ⟶ the language becomes …
Clear
Readable
Memorizable (less exceptions)
Attractive?
Brace Initialization: Solution (2)¶
Braces … int i{42};
int arr[]{1,2,3};
struct s { int i,j; }
s s1{1,2};
vector<int> v{1,2,3};
|
… many more braces class C {
public:
C() : data_{1,2,3} {}
private:
const int data_[3];
};
const int *arr = new const int[3]{1,2,3};
|