使用unique_ptr作为类成员变量

问题描述

我有一个Page,它需要一个Background对象(在我的项目中,每个页面都有背景)。 Background是其他类(例如RuledBackgroundDottedBackground)的基类,它们更详细地指定了背景。因此,我需要多态性,因此必须使用指针存储Background对象。但是,由于每个Page本质上都“拥有”一个唯一的Background对象,所以我想在std::unique_ptr<Background>类中使用一个Page,因此每个页面的背景都会自动删除页面被破坏时。下面的代码说明了我的类结构:

class Page{
public:
    Background* background() {
        return m_background.get();
    }
private:
    std::unique_ptr<Background> m_background;
};

在上面的代码中,我直接返回了原始指针作为背景,而不是返回unique_ptr,因为据我了解,传递原始指针是可以的(或者不是吗?)。我看到的方法存在的问题是要弄清楚如何从类外部初始化原始指针,诸如此类

    void setBackground(Background *bg){
        m_background = std::make_unique<Background>(bg);
    }

似乎很糟糕(因为我想我需要在某个地方创建原始指针)。 我考虑过的另一种方法是将unique_ptr设置为公共成员变量并返回对其的引用,然后可以从类外部对其进行初始化。 对于我刚刚描述的内容,最优雅,最安全的解决方案是什么?有没有比这更好的选择了?

解决方法

在我看来,您可能会想到import discord from discord.ext import commands,tasks bot = commands.Bot("$") channel_id = #Any ID #Message 1 @tasks.loop(seconds=5) async def called_once_a_day(): message_channel = bot.get_channel(channel id) await message_channel.send("test 1") @called_once_a_day.before_loop async def before(): await bot.wait_until_ready() print("Finished waiting") #Message 2 @tasks.loop(seconds=10) async def called_once_a_day2(): message_channel = bot.get_channel(channel id) await message_channel.send("test 2") @called_once_a_day2.before_loop async def before(): await bot.wait_until_ready() print("Finished waiting") called_once_a_day.start() called_once_a_day2.start() bot.run('token') ,好像它正在执行演员表转换一样。 make_unique将调用给定模板类型的构造函数并转发参数。假设您有不同的背景类:

make_unique

然后,您将拥有一个class Background { public: virtual ~Background() {} ...etc... }; class SimpleBackground : public Background { public: SimpleBackground () = delete; explicit SimpleBackground (int colourCode); virtual ~SimpleBackground () override {} ...etc... }; class TransitionBackground : public Background { public: TransitionBackground () = delete; TransitionBackground (int colourCode1,int colourCode2); virtual ~TransitionBackground () override {} ...etc... }; ,它可以根据某些给定的条件(例如,

)创建后台实例
factory method