shared_ptr作为引用引起的错误

#include <memory>
class Test{
public:
    Test(){
        std::cout<<"ctor"<<std::endl;
    }
    ~Test(){
        std::cout<<"dtor"<<std::endl;
    }
    void Print(const char *fun){
        std::cout<<"print "<<fun<<" "<<i_<<std::endl;
    }
    void Set(int i){
        i_=i;
    }
private:
    int i_{0};
};
void another_test(std::shared_ptr<Test> &t){
    std::shared_ptr<Test> t1=std::move(t);
    t1->Set(10);
    t1->Print(__FUNCTION__);
}
std::shared_ptr<Test> Create(){
    std::shared_ptr<Test> t(new Test());
    t->Set(5);
    return t;
}

int main(){
    std::shared_ptr<Test> t=Create();
    t->Print(__FUNCTION__);
    another_test(t);
    if(t){
        t->Print(__FUNCTION__);
    }
    printf("%d\n",t.use_count());
    return 0;
}

 代码中的if中的程序并不会被执行,且打印出的的引用计数为0。

   if(t){
        t->Print(__FUNCTION__);
    }
printf("%d\n",t.use_count());

 这里的错误就是another_test中引用参数造成的问题。改成如下的的,代码就可以正常执行。

void another_test(std::shared_ptr<Test> t){
    std::shared_ptr<Test> t1=std::move(t);
    t1->Set(10);
    t1->Print(__FUNCTION__);
}

[1]c++中智能指针Shared_ptr的原理https://www.jianshu.com/p/2331984bcd21

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容