(仅当零初始化为静态范围成员时才不是垃圾。)并且它有效 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
)我得到下一个输出:
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/