如何一个类树的一个分支的所有零初始化成员是垃圾? [英] How can one branch of class tree have all its Zero initialized members be rubbish?

查看:165
本文介绍了如何一个类树的一个分支的所有零初始化成员是垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(只有当零初始化为静态作用域成员时才是垃圾),并且其工作原理如同GCC中预期的那样() ((

(not rubbish only if zero initialized as static scope member.) and it works 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( ints enums )我得到下一个输出:

where all classes are generally PODs (ints, enums) I get next output:

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

而我期望所有的 0

为什么会发生这种情况?

Why can such thing happen?

推荐答案

编译器错误:根据此报告基类的成员在派生类的值初始化期间不是零初始化。

It appears to be a compiler bug: according to this report members of base classes are not zero-initialised during value-initialisation of the derived class.

就我所见,你的代码没有什么问题,所有的类成员都应该在一个合格的C ++ 03或C ++ 11编译器上进行初始化。

As far as I can see, there is nothing wrong with your code, and all class members should be zero-initialised on a conforming C++03 or C++11 compiler.

我想你的选择是:


  • 通过避免继承使类更像POD类似;或

  • 将默认构造函数添加到任何基类,以显式零初始化所有成员;或

  • 使用较少损坏的编译器。

这篇关于如何一个类树的一个分支的所有零初始化成员是垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆