Reputation: 10480
I've heard that the following is valid and leaves x
uninitialized as if it were int x;
:
int x = x;
What about this? Is this code equivalent to the above:
struct Foo
{
Foo(int Foo::*p) : x(this->*p) { }
int x;
};
int main() {
Foo f(&Foo::x);
}
Is f.x
still uninitialized? Do I have undefined behavior?
Upvotes: 4
Views: 190
Reputation: 158469
C++14 makes it clear that using an indeterminate value is undefined behavior, from section 8.5
(emphasis mine):
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17 [expr.ass]). [Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2 [basic.start.init]. —end note] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:
The only exceptions being in the case of unsigned char. Which is probably why they changed the example section 3.3.2 from:
int x = 12;
{ int x = x; }
To:
unsigned char x = 12;
{ unsigned char x = x; }
I do not see any exceptions that would exclude your example.
x
has an indeterminate value until it is initialized but then you access its value during the initialization which invokes undefined behavior.
Upvotes: 2
Reputation: 596121
Is this code equivalent to the above:
I would think so, yes, because you are essentially doing : x(x)
, just using a pointer to read the current value of x
as the input value, but x
has not been initialized yet.
Upvotes: 1