0
点赞
收藏
分享

微信扫一扫

C艹智能指针循环引用例子

言诗把酒 2022-04-08 阅读 35
c++
class Wife;
class Husband
{
public:
    void setWife(const shared_ptr<Wife>& wife)
    {
        this->myWife = wife;
        cout << "myWife's use_count" << myWife.use_count() << endl;
    }
    ~Husband()
    {
        cout << "myWife's use_count" << myWife.use_count() << endl;

        cout << "Husband is deleted" << endl;
    }

private:
    shared_ptr<Wife> myWife;
    //weak_ptr<Wife> myWife;

};
class Wife
{
public:
    void setHusband(const shared_ptr<Husband>& husband)
    {
        this->myHusband = husband;
        cout << "myHusband's use_count" << myHusband.use_count() << endl;
    }
    ~Wife()
    {
        cout << "myHusband's use_count" << myHusband.use_count() << endl;

        cout << "Wife is deleted" << endl;
    }

private:
    //shared_ptr<Husband> myHusband;
    weak_ptr<Husband> myHusband;

};

int main()
{
    shared_ptr<Husband> husband(new Husband);
    shared_ptr<Wife> wife(new Wife);
    husband->setWife(wife);
    wife->setHusband(husband);

}
举报

相关推荐

C++——智能指针

【C++】智能指针

C++ 智能指针

C++智能指针

C\C++_指针_智能指针模板类

0 条评论