简体   繁体   中英

Can we initialize structure memebers through smart pointer in initialization list?

#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)
    {}
    */

};

Question1> I have found that I cannot use the second block of code to initialize structure members pointed by a smart pointer. Is it a general c++ rule that we just cannot do it.

Please discard this question if the answer to the first question is "You cannot do it".

Question2> As far as I know, the order of assignment on initialization list is based on the order of member variables definition. Assume that you can initialize the member variables through smart pointer. How can you guarantee the order so that the smart point is initialized always first?

If you don't need StructB to be an aggregate/POD type, then just give it a constructor too:

#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)) { }
};

Otherwise you can just use a factory function, so that it remains a POD type:

#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)) { }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM