C++ 智能指针四

/* 智能指针enable_shared_from_this模板类使用 */

#include <iostream>
#include <string>
#include <memory>           //智能指针头文件

/*
enable_shared_from_this适用场合:
    当类A被share_ptr管理,且在类A的成员函数里需要把当前类对象作为参数传给其他函数时,就需要传递一个指向自身的share_ptr。

    1.为何不直接传递this指针
              使用智能指针的初衷就是为了方便资源管理,如果在某些地方使用智能指针,某些地方使用原始指针,很容易破坏智能指针的语义,从而产生各种错误。

    2.可以直接传递share_ptr<this>么?
              答案是不能,因为这样会造成2个非共享的share_ptr指向同一个对象,未增加引用计数导对象被析构两次。

shared_from_this返回的share_ptr会和自身的share_ptr共享一个对象
*/

class Student:public std::enable_shared_from_this<Student>
{
public:
    std::shared_ptr<Student> getPtr()
    {
        //这个会产生一个新的std::shared_ptr<Student>对象
        //return std::shared_ptr<Student>(this);
        //正确用法
        //return shared_from_this();
    }
private:
    std::string _name;
    int age;
};

void test()
{
    //错误的示例,每个shared_ptr都认为自己是对象仅有的所有者
    std::shared_ptr<Student> stu1 = std::make_shared<Student>();
    std::shared_ptr<Student> stu2 = stu1->getPtr();

    //打印引用计数
    printf("stu1 use_count [%d] .\n", stu1.use_count());  //打印1
    printf("stu2 use_count [%d] .\n", stu2.use_count());  //打印1

    //Student对象将会被析构2次,触发断点
}

int main()
{
    test();
    getchar();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhanggaofeng/p/10294495.html