0
#include <boost/scoped_ptr.hpp>

class classA
{
protected:
    struct StructB
    {
        int iAge;
        double dPrice;
    };

    boost::scoped_ptr<StructB> m_scpStructB;

public:
    classA(int age, double price)
        : m_scpStructB(new StructB)
    {
        m_scpStructB->iAge = age;
        m_scpStructB->dPrice = price;
    }

    /* DO NOT COMPILE  <= second block
    classA(int age, double price)
        : m_scpStructB(new StructB),
          m_scpStructB->iAge(age),
          m_scpStructB->dPrice(price)
    {}
    */

};

質問 1> コードの 2 番目のブロックを使用して、スマート ポインターが指す構造体メンバーを初期化できないことがわかりました。それができないというのは一般的なC ++のルールですか?

最初の質問に対する答えが「あなたにはできない」である場合は、この質問を破棄してください。

質問2> 私の知る限り、初期化リストの割り当て順序は、メンバー変数の定義の順序に基づいています。スマート ポインターを使用してメンバー変数を初期化できるとします。スマート ポイントが常に最初に初期化されるように、どのように順序を保証できますか?

4

1 に答える 1

1

集約/POD タイプである必要 がない場合はStructB、コンストラクターも指定します。

#include <boost/scoped_ptr.hpp>

class classA
{
protected:
    struct StructB
    {
        StructB(int age, double price) : iAge(age), dPrice(price) { }

        int iAge;
        double dPrice;
    };

    boost::scoped_ptr<StructB> m_scpStructB;

public:
    classA(int age, double price) : m_scpStructB(new StructB(age, price)) { }
};

それ以外の場合は、ファクトリ関数を使用して、POD タイプのままにすることができます。

#include <boost/scoped_ptr.hpp>

class classA
{
protected:
    struct StructB
    {
        int iAge;
        double dPrice;

        static StructB* make(int age, double price)
        {
            StructB* ret = new StructB;
            ret->iAge = age;
            ret->dPrice = price;
            return ret;
        }
    };

    boost::scoped_ptr<StructB> m_scpStructB;

public:
    classA(int age, double price) : m_scpStructB(StructB::make(age, price)) { }
};
于 2012-07-11T18:32:15.783 に答える