I am trying to understand which of the following usage of shared pointer makes more sense as it gets inserted into a vector.
bar
takes a const reference of a shared pointer vs foo
that takes a copy. In both the cases, the passed-in parameter gets moved into a vector. The interesting part is the use_count
of a
in the caller remains 2 for foo
and bar
both which implies the the vector stores a "copy"?
Like if a shared_ptr is passed by a reference, its count doesn't increment. As soon as it's "moved" into a vector, it does. Does that mean vector isn't storing the reference to an original object a
?
class A
{
std::vector<std::shared_ptr<int>> _vec;
public:
void bar(const std::shared_ptr<int>& ptr)
{
_vec.emplace_back(std::move(ptr));
}
void foo(std::shared_ptr<int> ptr)
{
_vec.emplace_back(std::move(ptr));
}
};
int main()
{
auto sp = std::make_shared<int>();
A a;
// a.foo(sp); // use_count = 2
a.bar(sp); // use_count = 2
}