C 11标准8.5.4.3说:
“如果初始化列表没有元素而T是具有默认构造函数的类类型,则该对象是值初始化的.”
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; }
这是VC的错误吗?我的VC是最新的2012年11月CTP.
解决方法
8.5p8涵盖非聚合类类型的值初始化.在您的情况下,(非联合)类具有隐式声明的默认默认无参数构造函数(12.1p5),它不会被删除并且是微不足道的(同上).因此8.5p8的第二个子弹适用:
— 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,ifT
has a non-trivial default constructor,default-initialized;
所以A应该是零初始化的,程序应该打印0.
在以下程序中:
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正确输出0; gcc-4.6.3错误输出42; clang-3.0绝对疯狂并输出垃圾(例如574874232).
原文地址:https://www.jb51.cc/c/118838.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。