Junior — Middle
Explain the differences between smart pointers std::unique_ptr, std::shared_ptr, and std::weak_ptr in C++.
sobes.tech AI
Answer from AI
std::unique_ptr is a smart pointer that owns an object exclusively. It is non-copyable, only movable, which guarantees a single owner of the resource. When a unique_ptr is destroyed, it releases the managed object.
std::shared_ptr is a smart pointer with reference counting. Multiple shared_ptrs can own the same object. The object is deleted when the last shared_ptr is destroyed or reset.
std::weak_ptr is a weak reference to an object managed by shared_ptr. It does not affect the reference count and is used to prevent cyclic dependencies. To access the object, weak_ptr must be converted to shared_ptr via the lock() method.
Example:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> uptr = std::make_unique<int>(10);
// std::unique_ptr<int> uptr2 = uptr; // Error: cannot copy
std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
std::shared_ptr<int> sptr2 = sptr1; // Reference count increases
std::weak_ptr<int> wptr = sptr1; // Does not increase the count
if (auto spt = wptr.lock()) { // Check if the object is still alive
std::cout << *spt << std::endl;
}
}