c++ - "A()" vs. "A() = default;" vs. Implicit A()? -
#include <vector> // version 1 struct { std::vector<int> m_coll; // compiler generate ctor a() here }; // version 2 struct { std::vector<int> m_coll; a(){} }; // version 3 struct { std::vector<int> m_coll; a() : m_coll(){} }; // version 4 struct { std::vector<int> m_coll; a() = default; };
what differences between 4 versions?
is m_coll
guaranteed default-initialized in of these versions?
it easier consider various options whenever add datum. consider:
struct { int i; std::vector<int> coll; };
in case, compiler generates default c'tor you, i
uninitialized, you'll have set explicitly.
let's improve things:
struct b { int {}; std::vector<int> coll; };
for b
, compiler generates default c'tor you, i
initialized in-class, , default-constructed object of type b
initialized. suppose want add user-defined c'tor:
struct c { int {}; std::vector<int> coll; c(int const j) : i{j} {} };
adding user-defined c'tor suppresses automatic generation of default constructor. enable default c'tor, 1 can few different things:
struct d1 { int {}; std::vector<int> coll; d1(int const j) : i{j} {} d1(){} };
although above well-formed, find ugly. here d1(){}
is default c'tor, , i
appropriately initialized since has in-class initializer. however, more descriptive like:
struct d2 { int {}; std::vector<int> coll; d2(int const j) : i{j} {} d2() = default; };
this way, can read enabling default c'tor.
in experience, more helpful use default
whenever 1 needs enable default definition copy/move constructors , assignment operators , default definition virtual destructors.
long story short: use default
whenever need enable c'tor or assignment operator compiler otherwise suppress, or when need default definition virtual destructor.
Comments
Post a Comment