0

(ゼロが静的スコープメンバーとして初期化された場合にのみゴミではありません。)そしてそれは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

なぜそのようなことが起こるのでしょうか?

4

1 に答える 1

4

これはコンパイラのバグのようです。このレポートによると、基本クラスのメンバーは、派生クラスの値の初期化中にゼロで初期化されません。

私が見る限り、コードに問題はありません。すべてのクラスメンバーは、準拠するC++03またはC++11コンパイラでゼロ初期化する必要があります。

私はあなたのオプションは次のとおりだと思います:

  • 継承を回避することにより、クラスをよりPODのようにします。また
  • すべてのメンバーを明示的にゼロ初期化するために、デフォルトのコンストラクターを任意の基本クラスに追加します。また
  • 壊れにくいコンパイラを使用してください。
于 2013-01-24T13:11:58.037 に答える