Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unique pointer to a pointer memory management

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading