繁体   English   中英

C++ unique_ptr() 用法

[英]C++ unique_ptr() Usage

我只是想确保我正确理解了参考文献。

我有一个 A 类,它包含在它的构造函数中设置唯一指针

class CDebug
{
//....
public:
    ~CDebug();
}

class A
{
public:
    A()
    {
        pDebug = unique_ptr<CDebug>(new CDebug());

        if(nullptr == pDebug)
        {
             CException ex("Nullpointer", __FILE__,__LINE__);
             throw ex;
        }
    }
private:
     unique_ptr<CDebug> pDebug;
}

现在,当 A 的实例离开它的作用域时:

  1. 在唯一的 Pointer 对象上自动调用 Delete Operator 以释放堆
  2. 这会强制析构~CDebug()运行

现在我是对的还是我在这里有任何内存泄漏?

回答你的问题:不会,内存不会泄露。 每当对象 A 超出范围时,将调用析构函数,其中将调用 CDebug 的析构函数并释放内存。

但是当人们想要学习如何使用 unique_ptr 时我很高兴,我想在代码中指出两件事。

首先,A 的构造函数中的 nullptr 检查是多余的。

A()
{
    pDebug = unique_ptr<CDebug>(new CDebug()); //throws at bad allocation

    if(nullptr == pDebug) // will never be true
    {
         CException ex("Nullpointer", __FILE__,__LINE__);
         throw ex;
    }
}

, pDebug永远不会是 nullptr。 如果使用 new 分配失败,则会抛出 std::bad_alloc 。 当然,除非您使用的是不支持异常处理的编译器。

其次——假设你有一个 C++14 编译器——避免使用 new。 通过调用 std::make_unique() 创建一个 unique_ptr。 它不仅具有从代码中删除 new/delete 的优点,而且它也是异常安全的(参见https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ )。

A()
{
    pDebug = std::make_unique<CDebug>();
    [...]
}

此外,如果您不是绝对必须在代码中抛出自定义异常,请将构造放在初始化程序列表中。

A() : pDebug(std::make_unique<CDebug>()) {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM