C++ .release()
In C++, the .release() function is a member of the smart pointer class std::unique_ptr. It releases ownership of the managed object and returns a raw pointer to that object. After calling .release(), the unique_ptr becomes empty and holds nullptr.
Syntax
If ptr is a std::unique_ptr, then:
ptr.release();
Parameters:
The function takes no parameters.
Return value:
Returns the raw pointer to the object managed by the unique_ptr before the call.
Example
This example demonstrates how to use .release():
#include <iostream>#include <memory>int main() {// Create a unique_ptr managing a new intstd::unique_ptr<int> auto_pointer(new int);// Assign value 10 to the managed object*auto_pointer = 10;// Release ownership and get the raw pointerint* manual_pointer = auto_pointer.release();// Output the value pointed to by manual_pointerstd::cout << "manual_pointer now points to " << *manual_pointer << "\n";// Manually delete the raw pointer to avoid memory leakdelete manual_pointer;return 0;}
The output of this code is:
manual_pointer now points to 10
This code creates a unique_ptr managing an integer with value 10. Calling .release() transfers ownership to manual_pointer, and the raw pointer must be manually deleted to prevent a memory leak.
Codebyte Example
In this codebyte example, std::unique_ptr is used to manage a FILE*. When there is a need to pass the file pointer to a legacy C-style API that expects a raw FILE*, .release() is used to transfer ownership safely:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours