C/C++ Arena

shared_ptr counts its owners

first and second point at the same heap int, and the use count says how many owners it has. When second goes out of scope at the end of the inner block, the count drops back to 1, and the object lives on because first still owns it.

#include <iostream>
#include <memory>

int main() {
    auto first = std::make_shared<int>(42);
    {
        std::shared_ptr<int> second = first;
        *second += 1;
        std::cout << first.use_count() << "\n";
    }
    std::cout << *first << " " << first.use_count() << "\n";
    return 0;
}

Output:

2
43 1

From the lesson: Smart pointers