Quantcast
Viewing latest article 6
Browse Latest Browse All 49

Too Subtle?

Spot the difference between the two C++ programs

struct S { int a = b, b; };
int main() { return (new S())->a; }

and

struct S { int a = b, b; };
int main() { return (new S)->a; }

Right, the first one terminates cleanly with exit code zero, while the second one does whatever it deems necessary to counter undefined behavior.

Why is that? The expression new S() means direct-initialization, which for () means value-initialization. Class S has a default constructor that is not user-provided, not deleted, and non-trivial (because non-static data member a has a default member initializer). So the instance of S is first zero-initialized, then default-initialized. Zero-initialization means that a and b are initialized to zero. Default-initialization for S means that the default constructor is called, which means that a is initialized from its default member initializer, by copying zero from b (and then b is default-initialized, leaving it alone).

On the other hand, just new S (without the parentheses) means just default-initialization (without previous zero-initialization). So, again, default-initialization for S means that the default constructor is called, which means that a is initialized from its default member initializer, copying the uninitialized b (and then b is default-initialized, leaving it uninitialized)…

Too subtle? Probably.


Viewing latest article 6
Browse Latest Browse All 49

Trending Articles