A BIG bug of VC++? Why does initializer

The C++11 standard 8.5.4.3 says:

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

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 bug of VC++? My VC++ is the latest Nov 2012 CTP.


Value-initialization of a non-aggregate class type is covered by 8.5p8. In your case the (non-union) class has an implicitly-declared defaulted default no-parameter constructor (12.1p5), which is not deleted and is trivial (ibid). Thus the second bullet of 8.5p8 applies:

— if T is a (possibly cv-qualified) non-union class type without a user-provided or deleted default constructor, then the object is zero-initialized and, if T has a non-trivial default constructor, default-initialized;

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

On 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 incorrectly outputs 42 ; clang-3.0 goes absolutely crazy and outputs garbage (eg 574874232 ).

链接地址: http://www.djcxy.com/p/11612.html

上一篇: 在重定向后对闪存消息进行功能测试

下一篇: VC ++的一个大错误? 为什么初始化器