Home > Software engineering >  Unique pointer to a pointer memory management
Unique pointer to a pointer memory management

Time:09-08

Function f allocates a few bytes that are returned in the form of a unique_ptr<char*>. How "smart" is this smart pointer ? When the returned unique_ptr goes out of scope, are those allocated bytes returned to the system ?

The managed object here is a pointer (char*), not the bytes it points to ! (hence the specialization for arrays)

Answer @Miles Budnek

No. Consider a unique_ptr<char[]>.

CodePudding user response:

std::unique_ptr is a very simple class template. All it does is store a pointer and delete (or delete[], in the case of an array) the object pointed to by that pointer in its destructor.

That is, it looks something like this (slightly simplified):

template <typename T>
class unique_ptr
{
private:
    T* ptr_;

public:
    unique_ptr(T* ptr)
      : ptr_{ptr}
    {}

    ~unique_ptr()
    {
        delete ptr_;
    }

    // Other constructors and member functions omitted for brevity
};

As you can see, all it does is delete the the object directly pointed to by the pointer it holds. If that object is itself a pointer then any data pointed to by that pointer does not get deleted.


If you want to return a smart pointer to an allocated array of char, then you should create a std::unique_ptr<char[]> pointing directly to the first char in the array. If you really want an extra level of indirection, you would need something like a std::unique_ptr<std::unique_ptr<char[]>> if you wanted the underlying array to get delete[]ed when the unique_ptr goes out of scope.

  • Related