[英]Replacing shared_ptr elements in std::vector
我有一個shared_ptrs向量,如下所示。
std::vector<std::shared_ptr<SharedThing>> things;
現在讓我們說我將一些shared_ptrs推送到向量上,每個元素現在的引用計數為1。
當我需要用新的shared_ptr替換其中一個元素時,我希望舊的shared_ptr超出范圍。 常規元素賦值是否會實現,或者只是復制shared_ptr內容。 例如:
things.at(0) = new_shared_ptr;
這會減少things.at(0)的引用計數並增加new_shared_ptr的計數嗎?
當我需要用新的shared_ptr替換其中一個元素時,我希望舊的shared_ptr超出范圍。 常規元素分配會實現嗎?
向量中的共享指針不會超出范圍,
但它會用給定的新對象替換托管對象。
呼叫:
things.at(0) = new_shared_ptr;
將計數保持在1。
以下是觀察此行為的簡便方法:
#include <iostream>
#include <vector>
#include <memory>
int main(){
//vector with a shared pointer
std::vector<std::shared_ptr<int>> things;
things.push_back(std::make_shared<int>(1));
//prints 1
std::cout << things.at(0).use_count() << '\n';
//assign a new value
things.at(0) = std::make_shared<int>(2);
//still prints 1
std::cout << things.at(0).use_count() << '\n';
}
雖然不是您問題的一部分,但通常建議使用make_shared
而不是new
。
是的,基本上你是對的。
為了更准確,將減少(0)處的先前shared_ptr的引用計數。 然后你給它分配一個新的shared_ptr,它可能有一個計數1.看起來(0)的引用計數是相同的,但它改變了並且改回來了。
您可以通過std :: shared_ptr :: use_cout()驗證它
有關更多詳細信息,我們可以調試到STL,當things.at(0) = new_shared_ptr;
包括/ C ++ / 4.8.3 /比特/ shared_ptr_base.h:556
__shared_count&
operator=(const __shared_count& __r) noexcept
{
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
if (__tmp != _M_pi)
{
if (__tmp != 0)
__tmp->_M_add_ref_copy();
if (_M_pi != 0)
_M_pi->_M_release();
_M_pi = __tmp;
}
return *this;
}
新的_M_add_ref_copy(),然后是前一個_M_release(),它將_M_use_count減少1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.