"utab" <um********@gmail.com> wrote in message
news:11*********************@i40g2000cwc.googlegro ups.com...
Can somebody direct me to some resources on the subject or explain the
details in brief? I checked the FAQ but could not find or maybe missed.
Here is a very brief summary:
When a type name or constructor initializer is followed by () [i.e. a pair
of parentheses with only whitespace between them], that calls for value
initialization. The difference between value initialization and the way
local variables are initialized is that value initialization gives an
initial value of zero to members that are out of reach of any constructor.
Here is an example:
struct A {
int x;
int y;
};
struct B {
int x;
std::string s;
};
struct C {
int x;
int y;
C() { }
};
If we write the following:
void foo()
{
A a;
B b;
C c;
}
then the local variables a, b, and c are all default-initialized. That
means that a.x and a.y, b.x, c.x, and c.y all have undefined values. On the
other hand, b.s is initialized to a null string, because that is what the
std::string constructor does.
Now, suppose we do this:
void bar()
{
A a = A();
B b = B();
C c = C(); // undefined behavior!
}
In each case we are value-initializing an otherwise nameless object (by
writing A(), B(), and C() respectively), and copying the value of that
object to the appropriate local variable.
In the case of A(), the x and y members will both be set to zero, because
they are out of reach of any constructor.
In the case of B(), the x member will be set to zero, for exactly the same
reason as the x member of A(); the s member will be initialized to a null
string by its own constructor.
In the case of C(), there is a constructor that is capable of initializing
the x and y members, so no initialization takes place. Attempting to copy
C() to c therefore results in undefined behavior.
The idea behind value initialization is that it takes place when an object
is about to be used in a context that demands a value--that is, when it is
about to be copied. When I write
A a;
there is no request to copy the variable "a", but when I write
A a = A();
there is a request to copy the nameless object represented by A(). For
example, if I had written
int x = int();
this definition would have undefined behavior unless int() had a
well-defined value, so int() is value-initialized to zero.
Incidentally, it would have a totally different meaning if I were to write
A a();
which would declare "a" as a function with no arguments returning an object
of type A.
As for constructor initializers:
struct S {
A a;
S(): a() { }
};
The member initializer "a" is followed by a pair of parentheses, so this
example demands value initialization. In other words, if I write
void foo()
{
S s;
}
then s.a.x and s.a.y will both be initialized to zero because of value
initialization.