[英]Can a trivial type class be copied when not all its members are initialized?
[英]How can one branch of class tree have all its Zero initialized members be rubbish?
(仅当零初始化为静态作用域成员时才是垃圾。)它在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
!
为什么会发生这种事情?
它似乎是一个编译器错误:根据此报告 ,基类的成员在派生类的值初始化期间没有被零初始化。
据我所知,您的代码没有任何问题,所有类成员都应在符合标准的C ++ 03或C ++ 11编译器上进行零初始化。
我想您的选择是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.