Search code examples
c++c++11memory-managementshared-ptrunique-ptr

How to take ownership of std::unique_ptr and std::shared_ptr


This is follow-up question for this.

How do we take ownership of a std::unique_ptr or std::shared_ptr?

Is there a way to to keep b alive?

class A{
  public:
   A() {
        b = std::unique_ptr<char[]>(new char[100] { 0 });
   }
 char* b;
}

void func {
   A a;
}

Solution

  • To take ownership of the pointer, use std::unique_ptr::release():

    Releases the ownership of the managed object if any.

    Return value. Pointer to the managed object or nullptr if there was no managed object, i.e. the value which would be returned by get() before the call.


    That being said, I'm not sure why you'd ever want to do b = std::unique_ptr<char[]>(new char[100] { 0 }).release();. Maybe what you want is this, i.e. have A itself store the unique_ptr?

    class A {
        A() : b(new char[100] { 0 }) { }
    
    private:
        std::unique_ptr<char[]> b;
    }    
    

    Now, whenever an A instance is destructed, the memory pointed to by A.b will be freed.