BIG VC ++ error? Why does the list initializer not initialize the structure?

The C ++ 11 8.5.4.3 standard says:

"If there are no elements in the initializer list, and T is the class type with the default constructor, the object is initialized with a value."

struct A { int get() { return i; } private: int i; }; int main() { A a = {}; int n = a.get(); cout << n << endl; // n is a random number rather than 0 return 0; } 

Is this a VC ++ bug? My VC ++ is the last November 2012 CTP.

+7
source share
1 answer

Initialization of values โ€‹โ€‹of type of non-aggregate class is covered by 8.5p8. In your case, the (non-union) class has an implicitly defaulted default constructor with no parameters (12.1p5), which is not deleted and is trivial (ibid). So the second bullet is 8.5p8:

- if T is a (possibly cv-qualified) class of non-union type without a user-supplied or removable default constructor, then the object is initialized to zero and if T has a nontrivial default value, the default initialized constructor;

So, A must be zero initialized, and the program should print 0 .

In the following program:

 struct A { int get() { return i; } private: int i; }; #include <iostream> int main() { char c[sizeof(A)]; new (c) int{42}; std::cout << (new (c) A{})->get() << '\n'; } 

gcc-4.7.2 correctly outputs 0 ; gcc-4.6.3 displays 42 incorrectly; clang-3.0 goes absolutely crazy and dumps garbage (e.g. 574874232 ).

+3
source

All Articles