从类成员返回智能指针的正确方法?
The right way to return a smart pointer from a class member?
我正在尝试在 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
不幸的是,我不明白这个问题,我不知道如何解决?
std::unique_ptr
的复制构造函数被隐式删除,因为它具有显式定义的移动构造函数。
从 C++11 标准 12.8 复制和移动类对象:
7 如果类定义未显式声明复制构造函数,则隐式声明一个。如果类定义声明移动构造函数或移动赋值运算符,则隐式声明的复制构造函数定义为已删除;否则,它被定义为默认值 ([dcl.fct.def])。
您可以通过以下方式解决问题:
-
返回对
Person
的引用。static Person& getInstance(); Person& Person::getInstance() { static Person p; return p; }
-
返回
shared_ptr<Person>
.static std::shared_ptr<Person> getInstance(); std::shared_ptr<Person> Person::getInstance() { static std::shared_ptr<Person> p(new Person); return p; }
我推荐第一种解决方案,因为它更简单。
PS请注意,它们都不需要使用static
成员变量instance
。
相关文章:
- 将一个类的方法指针存储到另一个类中
- 如何调用返回类方法指针的类方法
- 通过reinterpret_casting方法指针从指针调用派生类的方法。这是 UB 吗?
- 泛型方法指针.reinterpret_cast指向不同类的方法指针,这是 UB 吗?
- C++;类方法指针;λ;将 lambda 作为成员函数指针传递;
- 使用模板、方法指针和字符串键入推导
- 将方法指针作为整数参数发送到C#的C 方法
- 从C 中的VTable获取方法指针
- 模板化方法指针 - 无法匹配函数参数的指针
- 获取特定的模板重载方法指针
- 如何将方法指针声明为Typedef方法参数
- 如何将方法指针类型转换为函数指针类型
- 如何在使用 pthreads 时将方法指针作为函数参数传递C++
- 方法指针映射,编译器说他们不接受任何参数
- C# 方法指针,如 C++ 中的指针
- c++创建新的LinkedList类:Clear()方法指针被释放未分配
- 尝试获取类方法指针时出现E_NOINTERFACE
- 传递和强制转换方法指针
- 常量方法指针的类型是什么
- 将对象的方法指针传递给接受 [静态方法指针/全局函数] 指针的函数