The reset()
and release()
functions are both members of std::unique_ptr
, but they serve different purposes in managing the ownership of the pointed-to object. Let's dive into each one:
reset()
FunctionThe reset()
function does two things:
Here's an example:
#include <iostream>
#include <memory>
class Character {
public:
std::string Name;
};
int main() {
auto Frodo{std::make_unique<Character>("Frodo")};
std::cout << "Before reset: " << Frodo->Name << '\n';
Frodo.reset(new Character("Samwise"));
std::cout << "After reset: " << Frodo->Name << '\n';
Frodo.reset();
std::cout << "After reset to nullptr: "
<< (Frodo ? Frodo->Name : "nullptr") << '\n';
}
Before reset: Frodo
After reset: Samwise
After reset to nullptr: nullptr
release()
FunctionThe release()
function, on the other hand:
unique_ptr
to null.Here's an example:
#include <iostream>
#include <memory>
class Character {
public:
std::string Name;
};
int main() {
auto Gandalf{std::make_unique<Character>("Gandalf")};
std::cout << "Before release: " << Gandalf->Name << '\n';
Character* RawPtr{Gandalf.release()};
std::cout << "After release: "
<< (Gandalf ? Gandalf->Name : "nullptr")
<< '\n';
std::cout << "Raw pointer: " << RawPtr->Name << '\n';
delete RawPtr; // Don't forget to delete!
}
Before release: Gandalf
After release: nullptr
Raw pointer: Gandalf
Memory Management:
reset()
handles memory deallocation for you.release()
leaves memory management to you.Ownership:
reset()
can transfer ownership to the unique_ptr
.release()
transfers ownership away from the unique_ptr
.Return Value:
reset()
doesn't return anything.release()
returns the raw pointer.In general, reset()
is safer and more commonly used, as it handles memory management automatically. Use release()
with caution, typically when you need to transfer ownership to a different memory management scheme.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to manage dynamic memory using unique pointers and the concept of memory ownership