Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

unique_ptr::release

Releases ownership of the returned stored pointer to the caller and sets the stored pointer value to nullptr.

pointer release();

Returns the stored pointer.

Use release to take over ownership of the raw pointer stored by the unique_ptr. The caller is responsible for deletion of the returned pointer. The unique-ptr is set to the empty default-constructed state. You can assign another pointer of compatible type to the unique_ptr after the call to release.

This example shows how the caller of release is responsible for the object returned:

// stl_release_unique.cpp
// Compile by using: cl /W4 /EHsc stl_release_unique.cpp
#include <iostream>
#include <memory>

struct Sample {
   int content_;
   Sample(int content) : content_(content) {
      std::cout << "Constructing Sample(" << content_ << ")" << std::endl;
   }
   ~Sample() {
      std::cout << "Deleting Sample(" << content_ << ")" << std::endl;
   }
};

void ReleaseUniquePointer() {
   // Use make_unique function when possible.  
   auto up1 = std::make_unique<Sample>(3);
   auto up2 = std::make_unique<Sample>(42);
   
   // Take over ownership from the unique_ptr up2 by using release
   auto ptr = up2.release();
   if (up2) {
      // This statement does not execute, because up2 is empty.
      std::cout << "up2 is not empty." << std::endl;
   }
   // We are now responsible for deletion of ptr.
   delete ptr;
   // up1 deletes its stored pointer when it goes out of scope.   
}

int main() {
   ReleaseUniquePointer();
}

Computer output:

Constructing Sample(3)
Constructing Sample(42)
Deleting Sample(42)
Deleting Sample(3)

Header: <memory>

Namespace: std

Show:
© 2014 Microsoft