Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing shared_ptr elements in std::vector

I have a vector of shared_ptrs as below.

std::vector<std::shared_ptr<SharedThing>> things;

Now let's say I push a number of shared_ptrs onto the vector and each element now has a reference count of 1.

When I need to replace one of those elements with a new shared_ptr I want the old shared_ptr to go out of scope. Will regular element assignment achieve this or will it just copy the shared_ptr contents. For example:

things.at(0) = new_shared_ptr;

Will this decrement the reference count of things.at(0) and increment the count of new_shared_ptr?

like image 574
Stephen Blinkhorn Avatar asked May 26 '26 17:05

Stephen Blinkhorn


1 Answers

When I need to replace one of those elements with a new shared_ptr I want the old shared_ptr to go out of scope. Will regular element assignment achieve this?

The shared pointer in the vector won't go out of scope,
but it will replace the managed object with the new one given.

Calling:

things.at(0) = new_shared_ptr;

will preserve the count at 1.

Here is an easy way to observe this behaviour:

#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';
}

Although not a part of your question, it is often advised to use make_shared instead of a new.

like image 154
Trevor Hickey Avatar answered May 30 '26 02:05

Trevor Hickey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!