1

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.