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

MiD*_*MiD 0 c++ pointers

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

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)

提前致谢!

Joh*_*ith 7

这样做的惯用方法是:

class Foo
{
    std::unique_ptr<stEx> E;
    int index;
public: 
    Foo() : E(std::make_unique<stEx>()), index(0)
    {}
};
Run Code Online (Sandbox Code Playgroud)
  • 使用初始化列表
  • 使用make_unique(从不输入new)
  • 没有析构函数

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