Re: Initializers
Michael Tsang wrote:
I'm very confused among different types of initializations:
zero-initialize:
scalar: set to 0
class/array: initialize recursively
union: initialize first member
reference: no-op
Huh? Where do you get the "no-op"?
default-initialize:
class: call default constructor
array: initialize recursively
reference: ill-formed
others: no-op
value-initialize:
class with user-provided constructor: call default constructor
non-union class without user-provided constructor: zero-
initialise and call non-trivial constructor
array: initialize recursively
reference: ill-formed
others: zero-initialize
implicitly-defined default constructor:
default-initialize base classes and members recursively
When the direct initializer is (), the object is value-initialized but
consider the following:
#include <iostream>
struct A
{
A()
{
std::cout << "test" << std::endl;
}
int x;
};
struct B
{
// non-trivial implicit default constructor
A a;
int x;
};
A x; // x is zero-initialized and then default initialized so that x.x
== 0
int main()
{
A *p = new A; // p->x is not determined.
A *q = new A(); // q->x is also not determined?! A
standard caveat?!
Why is that a caveat? If you provide the default constructor and
*purposefully* omit 'x' from the initializer list, it's left
uninitialized no matter whether you use parens here or not.
delete p;
delete q;
B *r = new B; // default-initialized recursively: s->x
and s->a.x are both indeterminate.
B *s = new B(); // zero-initialized first: s->x and s->a.x
are both 0
Zero-initialized first? Where do you get that? It's not static.
The dynamic B object is value-initialized, yes (see 5.3.4/15)? And
since 'B' is an aggregate (no user-defined c-tors, no private or
protected non-static members, no virtual functions, no base classes), to
value-initialize it means that every non-static member and every base
class is value-initialized. And since 'A' has a user-defined c-tor, to
value-initialize it means to call that c-tor.
So, nope. Since 'A' has a user-declared c-tor, s->a.x is still
uninitialized!
}
Also, how does zero-initializing a reference make sense?
There ain't no such a thing as "zero-initializing a reference".
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask