C++ .reset()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 14, 2025
Contribute to Docs

The .reset() method is used with smart pointers in C++ (such as std::unique_ptr and std::shared_ptr). It releases ownership of the currently managed object (deleting it if this is the last owner) and optionally takes ownership of a new object passed as a raw pointer.

This method safely manages dynamic memory by deleting the previously managed object (if any), thereby helping to prevent memory leaks.

  • 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

Syntax

ptr.reset();              // Releases ownership and deletes the managed object
ptr.reset(raw_ptr);       // Releases current object and takes ownership of raw_ptr

Example

This example demonstrates how .reset() releases ownership of the managed object, deletes it, and sets the pointer to null:

#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr(new int(42));
std::cout << "Value before reset: " << *ptr << std::endl;
ptr.reset(); // Releases ownership and deletes the managed object
if (!ptr) {
std::cout << "Pointer is null after reset." << std::endl;
}
return 0;
}

The output of this code is:

Value before reset: 42
Pointer is null after reset.

In this example:

  • A std::unique_ptr manages an int with a value of 42.
  • After calling .reset(), the managed object is deleted and the pointer becomes null.
  • The check if (!ptr) confirms the pointer was successfully reset.

Codebyte Example

Run the following example to understand how the .reset() method works:

Code
Output

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