Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

std::shared_ptr利用法

std::shared_ptrの利用法です。Infoインスタンスは内側のスコープ内で生成されて外側のスコープ内で破棄されていることが分かります。

struct Info
{
    Info(){
        printf("Info() %p\n", this);
    }
    Info(const Info& obj) = delete;
    Info(Info&& obj) = delete;
    Info& operator=(const Info& obj) = delete;
    Info& operator=(Info& obj) = delete;
    ~Info(){
        printf("~Info() %p\n", this);
    }
    void dance(void){
        printf("dance! %p\n", this);
    }
};

int main(int argc, const char * argv[]) {
    
    std::shared_ptr<Info> a;
    {
        std::shared_ptr<Info> b;
        b = std::shared_ptr<Info>(new Info());
        b.get()->dance();
        a = b;
    }
    a.get()->dance();
    
    return 0;
}
Info() 0x100500000
dance! 0x100500000
dance! 0x100500000
~Info() 0x100500000

循環参照があるケースではstd::weak_ptrを使いますが、それはまた別の機会に。