c++ - 类树的一个分支如何使其所有零初始化成员都是垃圾?

标签 c++ visual-studio-2010 inheritance

(仅当零初始化为静态范围成员时才不是垃圾。)并且它有效 as expected on GCC!(((

所以对于这样的代码:

#include <iostream>
#include <boost/shared_ptr.hpp>

namespace SP
{
    // enums
    enum EnumMessage {
        EnumMessage_EventBase = 0,
        EnumMessage_EventServiceBase = 1,
        EnumMessage_OperationBase = 2
    };

    class Message;

    // define proxy class
    class Message  {
    public:
        EnumMessage _MessageCode;
    };

    class Parent : public Message {
    public:
        int _ServiceId;
        int _CallbackId;
    };

    class Child : public Parent {
    public:
        std::string _Debug;
    };

    class AnotherChild : public Parent {
    public:
        int _UserId;
    };
}

using namespace SP;

int main() {
    //OK
    static Child staticScopeChild = Child();
    boost::shared_ptr<Parent> ptrParent(new Parent());
    boost::shared_ptr<AnotherChild> ptrChild2(new AnotherChild());

    //Bad
    Child scopeChild = Child();
    boost::shared_ptr<Child> ptrChild(new Child());


    std::cout << "static " << staticScopeChild._MessageCode 
        << std::endl << "vs scope " << scopeChild._MessageCode 
        << std::endl << "vs pointer " << ptrChild->_MessageCode 
        << std::endl << "vs parent class pointer: " << ptrParent->_MessageCode 
        << std::endl << "vs another parent child: " << ptrChild2->_MessageCode <<std::endl;
    std::cin.get();
    return 0;
}

所有类通常都是 POD(intsenums)我得到下一个输出:

static 0
vs scope -858993460
vs pointer -842150451
vs parent class pointer: 0
vs another parent child: 0

虽然我希望所有的都是 0!

为什么会发生这样的事情?

最佳答案

这似乎是一个编译器错误:根据 this report基类的成员在派生类的值初始化期间未被零初始化。

据我所知,您的代码没有任何问题,所有类成员都应该在符合标准的 C++03 或 C++11 编译器上进行零初始化。

我猜你的选择是:

  • 通过避免继承使类更像 POD;或
  • 向任何基类添加默认构造函数以显式零初始化所有成员;或
  • 使用故障较少的编译器。

关于c++ - 类树的一个分支如何使其所有零初始化成员都是垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500962/

相关文章:

c# - 在 Outlook MailItem 中设置自定义 header

javascript - 为什么我的继承不起作用?

c++ - 在基类中设置一些值后,可以设置指向派生类的指针吗?

c++ - 无法在不破坏堆叠顺序的情况下使 QQuickWidget 背景透明

c++ - 从库 (DLL) 函数访问 ui 指针

visual-studio-2010 - 我可以在 Visual Studio 中使用 WinMerge 作为我的合并/差异工具吗?

java - 导入或实现可重用的静态数据?

c# - 如何通过 DllImport 将 double 组从 C# 传递到 C++

c++ - X代码 6.1 : All commands in Debug menu greyed out

javascript - Javascript 中的可折叠部分/区域(Visual Studio 2010/2012)