所以,这是我正在创建的一个类的示例:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
由于我希望E单独作为Foo对象的实例,因此当Foo对象被破坏时,E对象必须自动销毁,因此不应该比该对象更长.这就是我遇到智能指针的概念,特别是独特的指针.
但是,我似乎无法理解为什么我需要使用唯一指针.我如何销毁/释放一个独特的指针?
这是我尝试使用独特的指针.
#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; // ?
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
这样做的惯用方法是:
class Foo
{
std::unique_ptr<stEx> E;
int index;
public:
Foo() : E(std::make_unique<stEx>()), index(0)
{}
};
Run Code Online (Sandbox Code Playgroud)
new)此类型将自动启用移动,但禁用复制