What is the difference between unique_ptr, shared_ptr and weak_ptr?
| Type | Owners | Copy | Cost |
|---|---|---|---|
| unique_ptr | One | No (move only) | None |
| shared_ptr | Many | Yes | Reference count (atomic) |
| weak_ptr | None | Yes | Small |
#include <iostream>
#include <memory>
int main() {
auto u = std::make_unique<int>(1);
auto v = std::move(u); // move the ownership
auto s1 = std::make_shared<int>(2);
std::weak_ptr<int> w = s1; // does not increase the count
auto s2 = s1;
std::cout << (u == nullptr) << ' ' << s1.use_count() << ' ' << w.use_count() << '\n';
s1.reset();
s2.reset(); // the last owner is gone
std::cout << w.expired() << '\n';
std::cout << (w.lock() == nullptr) << '\n';
}
Output
1 2 2
1
1
Start with unique_ptr. Use shared_ptr only when ownership is really shared. weak_ptr breaks cycles, where two shared objects point to each other. See Smart Pointers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |