所以,这是我正在创建的类的示例:
typedef struct st{
int counter;
int fields[128];
}stEx;
class Foo {
stEx *E;
int index;
public :
Foo(){
this->index = 0;
this->E = new stEx;
}
~Foo(){
delete E;
}
}
因为我希望 E 单独成为 Foo 对象的实例,所以 E 对象必须在 Foo 对象被销毁时自动销毁,因此不应比该对象长寿。这就是我遇到智能指针概念的方式,尤其是唯一指针。
但是,我似乎无法理解为什么需要使用唯一指针。以及如何销毁/释放唯一指针?
这是我对独特指针的尝试。
#include <memory>
typedef struct st{
int counter;
int fields[128];
}stEx;
class Foo {
std::unique_ptr<stEx> E;
int index;
public :
Foo(){
this->index = 0;
this->E = std::unique_ptr<stEx>(new stEx());
}
~Foo(){
E.release; // ?
}
}
提前致谢!
执行此操作的惯用方法是:
class Foo
{
std::unique_ptr<stEx> E;
int index;
public:
Foo() : E(std::make_unique<stEx>()), index(0)
{}
};
- 使用初始化列表
- 使用 make_unique(永远不要输入
new
)
- 没有析构函数
此类型将自动启用移动,但禁用复制
我是一名优秀的程序员,十分优秀!