在单例中使用已删除的副本构造函数 [英] Use of deleted copy constructor in the singleton

查看:82
本文介绍了在单例中使用已删除的副本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了单例模式,例如,这里是我的代码:

I've implemented the singleton pattern like this, there is my code:

头文件:

class Settings_manager{
public:
    static Settings_manager& get_instance();

    void operator=(Settings_manager const&) =delete;
    Settings_manager(Settings_manager const&) =delete;
...

private:
    Settings_manager();
};

实现:

Settings_manager& Settings_manager::get_instance()
{
    static Settings_manager instance;
    return instance;
}

Settings_manager::Settings_manager()
{
    read_file();
}

当我尝试使用 get_instance main 中的c>函数是这样的:

When I try use get_instance function in main like this:

Settings_manager set = Settings_manager::get_instance();

Settings_manager set = std :: move(Settings_manager :: get_instance() );

我得到

error: use of deleted function 'Settings_manager::Settings_manager(const Settings_manager&)'
 Settings_manager set = Settings_manager::get_instance();

有人可以说出什么问题并加以解释吗?谢谢。

Can somebody tell, what's wrong and explain it? Thanks.

推荐答案

在这里考虑您要执行的操作:

Consider what you're trying to do here:

Settings_manager set = Settings_manager::get_instance();

您有自己的单身, get_instance() ,并且您要复制它?如果您可以...创建其中两个,那将有可能破坏单例的目的?

You have your singleton, get_instance(), and you're trying to copy it? That would kind of defeat the purpose of singleton if you could just... create two of them right?

您要使用引用

Settings_manager& set = Settings_manager::get_instance();

这样, set 单例实例。不是它的副本。

This way, set is the singleton instance. Not a copy of it.

这篇关于在单例中使用已删除的副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆