gpt4 book ai didi

c++ - 在这种情况下是否有必要使用 unique_ptr?

转载 作者:太空宇宙 更新时间:2023-11-04 14:40:56 24 4
gpt4 key购买 nike

所以,这是我正在创建的类的示例:

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)
  • 没有析构函数

此类型将自动启用移动,但禁用复制

关于c++ - 在这种情况下是否有必要使用 unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43234716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com