簡體   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>我發現我無法使用第二段代碼來初始化智能指針所指向的結構成員。 這是我們不能做的通用C ++規則嗎?

如果第一個問題的答案是“您不能做到”,請放棄此問題。

Question2>據我所知,初始化列表上的賦值順序基於成員變量定義的順序。 假設您可以通過智能指針初始化成員變量。 您如何保證訂單,以便始終先初始化智能點?

如果您不需要 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)) { }
};

否則,您可以只使用工廠函數,這樣它仍然是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