Search code examples
c++c++11vectorshared-ptr

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


Solution

  • 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, i.e., 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.