简体   繁体   中英

Appending an existing shared_ptr to a vector of shared_ptr

I have an existing vector of shared_ptr. I want to search through that vector and if a condition is met, copy the respective shared_ptr to a new vector.

...
//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? I'm pretty new to smart pointer.

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>& .
  • output_vec.push_back will create a new smart pointer, invoking the copy-constructor .
  • The copy constructor of std::shared_ptr :

    Constructs a shared_ptr which shares ownership of the object managed by 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:

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

2) In particular, this for-each can be synthesized with copy_if .

I am guessing that this will copy the shared_ptr

Correct.

but not increase the ref_count of the original

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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