[英]std::shared_ptr use_count() value
有人可以幫我解釋為什么輸出是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;
}
您只有兩個共享指針: x
和z
。
請注意, 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);
這一行:
std::shared_ptr<int> const& y = x; //doesn't increase use_count()
將y
聲明為x
的引用。 它就像是同一個對象的另一個名稱。 沒有創建std::shared_ptr
對象來增加引用計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.