【发布时间】:2018-05-04 22:13:56
【问题描述】:
我正在尝试在 person 类中编写单例模式,这使我能够为该类创建一个实例,并且我可以在程序的任何位置使用它。
以下是类:
// The declaration
class Person {
static unique_ptr<Person> instance;
Person() = default;
Person(Person&) = delete;
Person& operator=(const Person&) = delete;
~Person() = default;
public:
static unique_ptr<Person> getInstance();
};
// The implementation
unique_ptr<Person> instance = NULL;
unique_ptr<Person> Person::getInstance() {
if (instance == NULL) {
instance = unique_ptr<Person>(new Person());
}
return instance;
}
但它给我这个错误的问题是:Error C2280 'std::unique_ptr<Person,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
很遗憾,我不明白那个问题,也不知道如何解决?
【问题讨论】:
-
您希望从返回
unique_ptr<Person>而Person&不会提供给您的信息中得到什么?unique_ptr中的 "unique" 表示尝试复制它将失败。 -
std::unique_ptr有一个明确删除的复制构造函数。不能复制,但是可以参考*uniquePtr或者移动std::unique_ptr -
@Justin 想想如果你
move单身会发生什么。 -
@user4581301 我很清楚会发生什么。我正在给 OP 直接翻译错误消息
-
这是正确方法可能是做其他事情的情况之一。这是一个关于更好替代方案之一的精彩文章的链接:stackoverflow.com/a/1008289/4581301。
标签: c++ c++11 singleton smart-pointers