简体   繁体   English

将现有的shared_ptr追加到shared_ptr的向量

[英]Appending an existing shared_ptr to a vector of shared_ptr

I have an existing vector of shared_ptr. 我已经有一个shared_ptr向量。 I want to search through that vector and if a condition is met, copy the respective shared_ptr to a new vector. 我想搜索该向量,如果满足条件,则将各自的shared_ptr复制到新向量。

...
//vector< shared_ptr<Foo> > main_vec; // which already has some data
vector< shared_ptr<Foo> > output_vec{};

for ( auto iter = main_vec.begin() ; iter != main_vec.end() ; ++iter )
{
  if ( (*iter)->bar() == true )
    output_vec.push_back( *iter );
}

return output_vec;
...

I am not convinced the above is correct?? 我不相信以上是正确的?? I am guessing that this will copy the shared_ptr but not increase the ref_count of the original, or am I over thinking this? 我猜想这将复制shared_ptr但不会增加原始文件的ref_count,还是我过度考虑了这一点? I'm pretty new to smart pointer. 我对智能指针还很陌生。

TIA TIA

I am not convinced the above is correct?? 我不相信以上是正确的??

In accordance with your requirement specification, that's correct. 根据您的需求规范,这是正确的。


If you want to know more... 如果您想了解更多...

In particular, the statement: 该声明特别是:

output_vec.push_back( *iter );

has the following effects: 具有以下效果:

  • *iter returns a reference to the smart pointer, ie, std::shared_ptr<Foo>& . *iter返回对智能指针的引用,即std::shared_ptr<Foo>&
  • output_vec.push_back will create a new smart pointer, invoking the copy-constructor . output_vec.push_back将创建一个新的智能指针,调用copy-constructor
  • The copy constructor of std::shared_ptr : std::shared_ptr的副本构造函数:

    Constructs a shared_ptr which shares ownership of the object managed by r. 构造一个shared_ptr,它共享由r管理的对象的所有权。

So the reference counter to the shared object will be increased. 因此,共享对象的引用计数器将增加。

Additional Notes... 补充笔记...

Just for the sake of completeness, I would add some personal suggestions. 为了完整起见,我将添加一些个人建议。

1) For-each loop can be expressed in a better way: 1) for-each循环可以用更好的方式表示:

for (const auto& ptr : main_vec) {
  if (ptr->bar()) output_vec(ptr);
}

2) In particular, this for-each can be synthesized with copy_if . 2)特别是,此for-each可以与copy_if合成。

I am guessing that this will copy the shared_ptr 我猜这将复制shared_ptr

Correct. 正确。

but not increase the ref_count of the original 但不增加原始文件的ref_count

No, the copy constructor does increase the reference count. 不,复制构造函数确实会增加引用计数。 That's how shared pointers are designed to be copyable. 这就是共享指针被设计为可复制的方式。

I am not convinced the above is correct? 我不相信以上是正确的吗?

Then let me convince you: It is correct. 然后让我说服您:是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM