C++ : 3 questions about initialization syntax, value-initialization and default-initialization -
so trying real hard understand rules of initialization in c++.
i wrote following code:
struct b { int i; // prevents definition of implicit default constructor b( int j ) : i(j) {} }; struct c { int i; // not mentioned in initializer list // compiler call default constructor c() {} }; int main() { int x( 1 ); cout << " x = " << x << endl; // error: no matching function call ‘b::b()’ //b b4 = b(); //cout << " b4.i = " << b4.i << endl; c c1; cout << " c1.i = " << c1.i << endl; }
1) x correctly initialized 1, don't understand notation "int x(1)". it's not value-initialized (we write "int x = int()", , x 0). it's not constructor call either, because built-in types not have constructors. besides, following page says that: "only objects of classes constructors can initialized function-style syntax".
http://msdn.microsoft.com/en-us/library/w7wd1177(v=vs.100).aspx
2) won't compile if uncomment creation of b4. because defined constructor, compiler doesn't generate implicit default constructor. fine. why prevent creation of temporary value-initialized object using "b()"? writing "b()" never constructor call, it?
3) explained in comments of class c, not mentioned in initializer list. therefore, should default-initialized, means undefined int type. output "c1.i = 0" every time run program.
thanks.
the notation
int x(1);
called direct-initialization. it's defined separately native types , classes. in latter case constructor called.in case, there no such thing value-initialization if there's no default constructor. rules constructing temporary same constructing named object.
reading uninitialized value produces undefined behavior. running same program again might produce same results, trying other programs, other machines, other platforms, may (or may not) make else happen. undefined literally means undefined standard, not crashing or random or producing error message.
for people rely on guarantees of best-available specs, includes smart folks, program undefined behavior incorrect , can assumed crash when least expect.
Comments
Post a Comment