简体   繁体   中英

C++ unique_ptr() Usage

I just want to make sure that i understood the reference correctly.

I got a class A that contains that sets the unique pointer within it's constructor

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;
}

Now when an instance of A leaves it scope:

  1. Delete Operator is called automatically on the unique Pointer object to free the heap
  2. This forces the Destructor ~CDebug() to run

Now am I right or do i get any memory leaks here?

To answer your question: no, memory will not be leaked. Whenever object A goes out of scope, the destructor will be called, where destructor for CDebug will be called and memory freed.

But as I am very happy when people want to learn how to use unique_ptr, I wanted to point out two things with the code.

Firstly, the nullptr check in the constructor for A is redundant.

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 will never be nullptr. If allocation with new fails, std::bad_alloc will be thrown. Unless, of course, you are working with a compiler that does not support exception handling.

Secondly - assuming you have a C++14-compiler - avoid using new. Create a unique_ptr by calling std::make_unique(). Not only does it have the advantage that new/delete are removed from code, but it is also exception safe (see https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ ).

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

Also, if you do not absolutely have to throw a custom exception in the code, put the construction in the initializer list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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