C++ .release()

core6662006317's avatar
Published Jul 14, 2025
Contribute to Docs

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.

  • 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

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 int
std::unique_ptr<int> auto_pointer(new int);
// Assign value 10 to the managed object
*auto_pointer = 10;
// Release ownership and get the raw pointer
int* manual_pointer = auto_pointer.release();
// Output the value pointed to by manual_pointer
std::cout << "manual_pointer now points to " << *manual_pointer << "\n";
// Manually delete the raw pointer to avoid memory leak
delete 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:

Code
Output
Loading...

All contributors

Contribute to 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