引用shared_pointer的引用计数

时间:2016-10-04 18:17:18

标签: c++ c++11 shared-ptr smart-pointers

我知道shared_ptr类会自动管理动态对象。

在这里,我有一个函数f,可以将const shared_ptr<int>返回给int 2

我有两个版本的main在一个地方有所不同。版本A将f的返回值保存到共享指针,而版本B保存到共享指针引用

 using namespace std;
    const std::shared_ptr<int> f() {
        const std::shared_ptr<int> ret = std::make_shared<int>(2);
        return ret;
    }

    int main () {
        const std::shared_ptr<int> p = f();     // A
        // const std::shared_ptr<int> &p = f(); // B
        cout << p.use_count() << *p << endl; // prints 1 2
        return 0;
    }

两个版本都打印1 2。我对版本A没问题,因为p是指向shared_ptr的最后int,因此use_count1

问题:为什么版本B的use_count等于1?最后一个shared_ptr在哪里?

1 个答案:

答案 0 :(得分:1)

在C ++中,如果您将临时值直接分配到&&const&,则引用生命周期扩展会启动,并且临时持续时间与引用一样长。

这仅适用于您的引用是局部变量 1

1 或者在某些使用struct s的汇总构造的编译器中。但是不要使用它,因为它是“透明”转发构造函数与聚合根本不同的地方之一,因此以后无害的更改可能会破坏您的代码。