C++ 从类成员返回智能指针的正确方法?
我试图在person类中编写singleton模式,这使我能够为该类创建一个实例,并且我可以在程序中的任何地方使用它 以下是课程:C++ 从类成员返回智能指针的正确方法?,c++,c++11,singleton,smart-pointers,C++,C++11,Singleton,Smart Pointers,我试图在person类中编写singleton模式,这使我能够为该类创建一个实例,并且我可以在程序中的任何地方使用它 以下是课程: // The declaration class Person { static unique_ptr<Person> instance; Person() = default; Person(Person&) = delete; Person& operator=(const 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;
}
//声明
班主任{
静态唯一_ptr实例;
Person()=默认值;
Person(Person&)=删除;
人员和操作员=(const Person&)=删除;
~Person()=默认值;
公众:
静态唯一_ptr getInstance();
};
//实施
unique_ptr instance=NULL;
唯一的\u ptr Person::getInstance(){
if(实例==NULL){
instance=unique_ptr(newperson());
}
返回实例;
}
但它给我这个错误的问题是:error C2280'std::unique\u ptr::unique\u ptr(const std::unique\u ptr&)':尝试引用已删除的函数
不幸的是,我不理解这个问题,也不知道如何解决?std::unique_ptr的复制构造函数被隐式删除,因为它有一个显式定义的移动构造函数 从: 7如果类定义没有显式声明副本构造函数,则隐式声明一个副本构造函数。如果类定义声明了移动构造函数或移动赋值运算符,则隐式声明的复制构造函数定义为已删除;否则,它被定义为默认值() 您可以通过以下方式解决问题:
人员的引用
static Person& getInstance();
Person& Person::getInstance()
{
static Person p;
return p;
}
共享\u ptr
static std::shared_ptr getInstance();
std::shared_ptr Person::getInstance()
{
静态标准::共享ptr p(新人员);
返回p;
}
PS请注意,它们都不需要使用
静态
成员变量实例
std::unique_ptr的复制构造函数被隐式删除,因为它有一个显式定义的移动构造函数
从:
7如果类定义没有显式声明副本构造函数,则隐式声明一个副本构造函数。如果类定义声明了移动构造函数或移动赋值运算符,则隐式声明的复制构造函数定义为已删除;否则,它被定义为默认值()
您可以通过以下方式解决问题:
人员的引用
static Person& getInstance();
Person& Person::getInstance()
{
static Person p;
return p;
}
共享\u ptr
static std::shared_ptr getInstance();
std::shared_ptr Person::getInstance()
{
静态标准::共享ptr p(新人员);
返回p;
}
PS请注意,它们都不需要使用
静态
成员变量实例
返回个人&
无法提供的唯一ptr
您希望得到什么?unique_ptr
中的“unique”表示尝试复制它将失败。std::unique_ptr
有一个显式删除的复制构造函数。它不能被复制,但是你可以引用*uniquePtr
,或者你可以移动std::unique\u ptr
@Justin想想如果你移动
单件会发生什么。@user4581301我知道会发生什么。我给OP一个错误信息的直接翻译,这是一个正确的方法可能是做其他事情的例子。这里有一个链接,指向一篇关于一个更好的选择的优秀文章:。你希望从返回一个唯一的
中得到什么,而人&
不会提供给你?unique_ptr
中的“unique”表示尝试复制它将失败。std::unique_ptr
有一个显式删除的复制构造函数。它不能被复制,但是你可以引用*uniquePtr
,或者你可以移动std::unique\u ptr
@Justin想想如果你移动
单件会发生什么。@user4581301我知道会发生什么。我给OP一个错误信息的直接翻译,这是一个正确的方法可能是做其他事情的例子。这里有一个链接,指向一篇关于更好的选择之一的精彩文章:。抱歉,但最后一行是什么意思?@LionKing它意味着您可以从Person
类声明中删除实例
成员变量(即,删除这行代码:静态唯一\u ptr实例;
)@雷米利博:谢谢。我希望我能不止一次地给出这个答案,但你说的最后一行是什么意思?@LionKing它意味着你可以从Person
类声明中删除实例
成员变量(即,删除这行代码:静态唯一\u ptr实例;
)@雷米利博:谢谢。我希望我能不止一次地给出这个答案