简体   繁体   English

我们可以通过初始化列表中的智能指针来初始化结构成员吗?

[英]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. Question1>我发现我无法使用第二段代码来初始化智能指针所指向的结构成员。 Is it a general c++ rule that we just cannot do it. 这是我们不能做的通用C ++规则吗?

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. Question2>据我所知,初始化列表上的赋值顺序基于成员变量定义的顺序。 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: 如果您不需要 StructB为聚合/ POD类型,那么也只需为其提供一个构造函数即可:

#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: 否则,您可以只使用工厂函数,这样它仍然是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)) { }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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