std :: shared_ptr use_count()值

ben*_*ros 2 c++ c++11

有人可以帮我解释为什么输出是2而不是3?谢谢.

int main()
{
    std::shared_ptr<int> x(new int);
    std::shared_ptr<int> const& y = x;
    std::shared_ptr<int> z = y;
    std::cout << x.use_count() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 8

你只有两个共享指针:xz.

请注意,这y是一个变量,但不是一个对象.它的类型是引用类型,而不是对象类型.

(在C++中,并非每个对象都是变量,并非每个变量都是对象.)

也许下面的代码说明在路上y不会持有股权的比例:

std::shared_ptr<int> x(new int());

std::shared_ptr<int> const& y = x;
assert(y.use_count() != 0);

x.reset();

assert(y.use_count() == 0);
Run Code Online (Sandbox Code Playgroud)


atr*_*ski 6

这一行:

std::shared_ptr<int> const& y = x; //doesn't increase use_count()
Run Code Online (Sandbox Code Playgroud)

宣称y只是一个参考x.它就像是同一个对象的另一个名称.没有std::shared_ptr创建对象来增加引用计数.