簡體   English   中英

std :: shared_ptr use_count()值

[英]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;
}

您只有兩個共享指針: 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);

這一行:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM