Junior — Middle
How is the guarantee of object uniqueness implemented using std::unique_ptr in C++?
sobes.tech AI
Answer from AI
std::unique_ptr in C++ implements a guarantee of unique ownership of an object through move semantics. It is a smart pointer that owns an object and guarantees that only one unique_ptr owns the resource at any given time.
Main points:
- Copying
unique_ptris prohibited (copy constructor and assignment operator are deleted), which prevents having multiple owners. - Moving a
unique_ptrtransfers ownership from one pointer to another, leaving the original pointer empty.
Example:
#include <memory>
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
// std::unique_ptr<int> ptr2 = ptr1; // Error: copying is prohibited
std::unique_ptr<int> ptr2 = std::move(ptr1); // Ownership transferred to ptr2
if (!ptr1) {
// ptr1 is now empty
}
Thus, std::unique_ptr ensures unique ownership of an object, preventing memory leaks and double deletion errors.