std::shared_ptr の基本動作

初期化、スコープによる解放、明示的解放の確認。

#include <memory>
#include <iostream>

class ToBeShared {
 public:
    ToBeShared() { std::cout << "ToBeShared Constructed. this="
                    << std::hex << this << std::endl; }
    ~ToBeShared() {std::cout << "ToBeShared Destructed. this="
                    << std::hex << this << std::endl; }
 };

int main() {
    auto printone = [](const std::string& name,
                       const std::shared_ptr<ToBeShared>& sp) {
        std::cout << name << "(" << std::hex << sp.get()
        << std::dec << ").use_count()= " << sp.use_count()
        << std::endl;
    };

    std::cout << "Creation" << std::endl;
    auto sp1 = std::make_shared<ToBeShared>();
    printone("sp1[make_shared]", sp1);
    auto sp2 = sp1;
    printone("sp2[copied sp1]", sp2);
    {   std::shared_ptr<ToBeShared> sp3;
        printone("sp3[defined]", sp3);
        sp3 = sp2;
        printone("sp3[copied sp2]", sp3);
    }  // = implicit delete
    std::cout << "sp3 out of scope." << std::endl;

    printone("sp2[before reset]", sp2);
    sp2.reset();  // = explicit delete

    printone("sp1[before reset]", sp1);
    sp1.reset();  // = explicit delete

    return 0;
}

実行結果。

Creation
ToBeShared Constructed. this=0x294f1eb03a0
sp1[make_shared](0x294f1eb03a0).use_count()= 1
sp2[copied sp1](0x294f1eb03a0).use_count()= 2
sp3[defined](0).use_count()= 0
sp3[copied sp2](0x294f1eb03a0).use_count()= 3
sp3 out of scope.
sp2[before reset](0x294f1eb03a0).use_count()= 2
sp1[before reset](0x294f1eb03a0).use_count()= 1
ToBeShared Destructed. this=0x294f1eb03a0