【发布时间】:2017-08-31 06:37:39
【问题描述】:
所以,这是我正在创建的一个类的示例:
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; // ?
}
}
提前致谢!
【问题讨论】:
-
使用
release会破坏目的。unique_ptr的目的是消除记住释放资源的负担。std::unique_ptr::release则相反,称其为您不希望对象被自动删除的声明。 -
考虑使用
std::make_unique<stEx>()而不是new。 -
你为什么还要在这里使用指针?为什么不让它成为该类的普通值成员,然后你会得到自动清理。
-
尝试复制构造或分配
Foo对象。 -
如果你想复制构造 Foo:见stackoverflow.com/questions/16030081/…