本文介绍了值初始化和非POD类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 一小时前我发布了一个答案这里根据我是正确的。但是我的回答被 Martin B 拒绝。他说但是在阅读Michael Burr的回答后,此处并尝试下面的示例代码 1) #include< cassert> struct B {〜B(); int m; }; int main() { B * b = new B(); assert(b-> m == 0); } 我在MSVC ++ 2010上遇到调试错误。 我遇到类似的错误,当我尝试下面的代码[我的回答此处] 2) #include< cassert> struct Struct { std :: string String; int Int; bool k; // add add add }; struct InStruct:Struct { InStruct():Struct(){} }; int main() { InStruct i; assert(i.k == 0); } (1)也不是(2)在gcc / Clang给了任何这样的错误,让我想如果MSVC ++ 2010不支持C ++ 03。我不确定。 根据Michael Burr的文章[在C ++ 03] 如果没有用户声明的默认构造函数编译器合成的默认构造函数将被调用,它将零初始化所有字段(根据最后一点)。 那么我错了什么? 解决方案 Visual Studio在所有当前版本(2005,2008,2010)中都有已知的错误它没有正确地实现没有用户声明的构造函数的非POD类型的值初始化。 根据语言规则,做展示编译器问题。这些是一些错误报告,注意它们都关闭或解决为不会修复。 http://connect.microsoft.com/VisualStudio/feedback/details/564268/c-value-initialization http://connect.microsoft.com/VisualStudio/feedback/details/484295/vc-does-not-value-initialize-members-of-derived-classes-without-user -declared-constructor http://connect.microsoft.com/VisualStudio/feedback/details/100744/value-initialization-in-new-expression An hour ago I posted an answer here which according to me was correct. However my answer was downvoted by Martin B. He saidHowever after reading Michael Burr's answer here and trying the following sample code1)#include <cassert>struct B { ~B(); int m; };int main(){ B * b= new B(); assert ( b->m ==0);}I got a debug error on MSVC++2010.I got a similar error when I tried the following code [My answer here] on MSVC++20102)#include <cassert>struct Struct { std::string String; int Int; bool k; // add add add};struct InStruct:Struct{ InStruct():Struct(){}};int main(){ InStruct i; assert( i.k == 0);}Neither (1) nor (2) gave any such error on gcc/Clang which made me think if MSVC++2010 does not support C++03. I am not sure.According to Michael Burr's post [in C++03]The Standard saysFrom the first point if there is no user declared default constructor the compiler synthesized default constructor will be called which will zero initialize all the fields (according to last point).So where am I wrong? Is my interpretation of value initialization correct? 解决方案 Visual Studio has known bugs in all current versions (2005, 2008, 2010) where it doesn't correctly implement value-initialization for non-POD types that don't have a user declared constructor.By the language rules none of you asserts should fire but do exhibit the compiler issues. These are some of the bug reports, note that they are all closed or resolved as "Won't Fix".http://connect.microsoft.com/VisualStudio/feedback/details/564268/c-value-initializationhttp://connect.microsoft.com/VisualStudio/feedback/details/484295/vc-does-not-value-initialize-members-of-derived-classes-without-user-declared-constructorhttp://connect.microsoft.com/VisualStudio/feedback/details/100744/value-initialization-in-new-expression 这篇关于值初始化和非POD类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-02 16:34