What is the difference between unique_ptr, shared_ptr and weak_ptr?

TypeOwnersCopyCost
unique_ptrOneNo (move only)None
shared_ptrManyYesReference count (atomic)
weak_ptrNoneYesSmall
#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.