C++11
=====
Based on Scott Meyers: Effective Modern C++
class X { ... };
X x1;
X x2 = x1;
x1 = x2;
Braced initialization in C++11:
===============================
Initializing containers:
std::vector<int> v{ 1, 2, 3 };
Normal Initialization:
int x( 0 );
int x = 0;
int x{ 0 };
int x = { 0 };
Initializing (non-static) data members:
class X
{
...
private:
int x{ 0 };
int y = 0;
int z( 0 );
};
Initializing non-copyable objects:
std::atomic<int> a1{ 0 };
std::atomic<int> a2( 0 );
std::atomic<int> a3 = 0;
Only { } can be used everywhere -> _uniform_ initialization
Narrowing conversions:
double d;
int i = d;
int i( d );
int i{ d };
Most wexing parse:
class X { ... };
X x1(10);
X x2;
X x3();
X x4{};
Auto
auto x1 = 1;
auto x2(1);
auto x3 = { 1 };
auto x4{ 1 };
auto x5 { 1, 2, 3.14 };
Compilers prefer braced initialization. Prefer very much!
class X
{
...
public:
X(int i, bool b);
X(int i, double d);
X(std::initializer_list<long double> il);
operator float() const;
...
};
X x1(10,true);
X x2{10,true};
X x3(10, 5.);
X x4{10, 5.};
X x5(x4);
X x6{w4};
X x7(std::move(x4));
X x8{std::move(x4)};
class Y
{
...
public:
Y(int i, bool b);
Y(int i, double d);
Y(std::initializer_list<bool> il);
};
Y y{10, 5.0};
Not initializer_list only when impossible
class Y
{
...
public:
Y(int i, bool b);
Y(int i, double d);
Y(std::initializer_list<std::string> il);
};
Y y{10, 5.0};
Empty brace means default contructor:
Z z1;
Z z2{};
Z z3();
Z z4({})
Z z4{{}}
Every-day samples
std::vector v1(10,0);
std::vector v2{10,0};
Delegating constructor
======================
class X
{
public:
X() : i_(0), k_(0) { }
X(int i) : i_(i), k_(0) { }
private:
int i_;
int k_;
};
class X
{
public:
X() { helper(0,0); }
X(int i) { helper(i,0); }
private:
void helper(int i, int k) { i_ = i; k_ = k; }
int i_;
int k_;
};
class X
{
public:
X() : i_(0), k_(0) { }
X(int i) : i_(i), k_(0) { }
private:
int i_;
int k_;
};
class X
{
public:
X() : X(0) { }
X(int i) : i_(i), k_(0) { }
private:
int i_;
int k_;
};
int main()
{
X w1;
X w2(1);
}
class X
{
public:
X() : X(0), k_(0) { }
X(int i) : i_(i), k_(0) { }
private:
int i_;
int k_;
};
c.cpp: In constructor ‘X::X()’:
c.cpp:4:19: error: mem-initializer for ‘X::k_’ follows constructor delegation
X() : X(0), k_(0) { }
§12.6.2/6) A mem-initializer-list can delegate to another constructor
of the constructor’s class using any class-or-decltype that denotes
the constructor’s class itself. If a mem-initializer-id designates
the constructor’s class, it shall be the only mem-initializer; the
constructor is a delegating constructor, and the constructor selected
by the is the target constructor. [...]