Reputation: 33
#include <string>
struct T1 { int mem; };
struct T2
{
int mem;
T2() { } // "mem" is not in the initializer list
};
int n; // static non-class, a two-phase initialization is done:
// 1) zero initialization initializes n to zero
// 2) default initialization does nothing, leaving n being zero
int main()
{
int n; // non-class, the value is indeterminate
std::string s; // class, calls default ctor, the value is "" (empty string)
std::string a[2]; // array, default-initializes the elements, the value is {"", ""}
// int& r; // error: a reference
// const int n; // error: a const non-class
// const T1 t1; // error: const class with implicit default ctor
T1 t1; // class, calls implicit default ctor
const T2 t2; // const class, calls the user-provided default ctor
// t2.mem is default-initialized (to indeterminate value)
}
Im currently looking at the reference guide, however there a a few things i don't understand.
I have run the above code, for the struct T2, the data member "int mem" is not in the initialiser list. It is said that t2.mem is default-initialized to an indeterminate value. But when i run this code, t2.mem seems to be zero initialised for me?
Upvotes: 3
Views: 518
Reputation: 2250
But when i run this code, t2.mem seems to be zero initialised for me?
No, in both cases (T1, T2), mem
is not initialized, or initialize by indeterminate value. The explicit declaration of the constructor in this case does not affect the mem
initialization. If you want to initialize mem
, you must do it explicitly in the member initializer list:
struct T2
{
int mem;
T2() : mem(0) { }
};
Or through the default member initializer:
struct T1 { int mem = 0; };
Or through aggregate initialization ofT1
, which is only takes place if T1
does not have any user declared constructors.
struct T1 { int mem; }
int main() {
T1 a{}; // aggregate initialization
assert(a.mem == 0)
T1 b; // default constructor does not value initialize mem
}
If you see that mem
initialized by 0
in the second case, then this is most likely a feature of the compiler, or you just get lucky with the 0
value. This is not guaranteed by the standard, don't rely on it.
Upvotes: 5