Yorda
Yorda

Reputation: 11

Is this proper usage of std::shared_ptr?

I was wondering if the following is correct usage of a std::shared_ptr. All I want to do with the originally created pointer is add it onto the vector on class A, which will be later on retrieved

class A
{
public:
   void AddToVec(std::shared_ptr<B> b)
   {
      myVec_.push_back(b);
   }

   std::vector<std::shared_ptr<B>> GetVec()
   {
      return myVec_;
   }
private:
   std::vector<std::shared_ptr<B>> myVec_;
}

Then on main, a pointer is created and passed with the following way

int main()
{
   A a;

   std::shared_ptr<B> ptr = std::make_shared<B>();
   a.AddToVec(std::move(ptr));
}
  1. Is the usage of the std::move correct on the main function?
  2. Is it okay to simply create the std::shared_ptr on main and move ownership using the AddToVec function?

Upvotes: 1

Views: 422

Answers (1)

JeJo
JeJo

Reputation: 32852

Is the usage of the std::move correct on the main function?

Yes, it is correct. If you do not use the std::move, it will also compile; however, it increases the reference count of std::shared_ptr.


Is it okay to simply create the shared ptr on main and move ownership using the AddToVec function?

It is correct in the sense, you do not want to increment the reference count of the std::shared_ptr. The same you need inside AddToVec, as the b is lvalue reference inside the function scope. Therefore, you need to explicitly std::move into the myVec_ as follows:

void AddToVec(std::shared_ptr<B> b)
{
    myVec_.push_back(std::move(b));
}

Also note that the GetVec will return each time a copy of the member myVec_, which you might not want. Therefore, you might need one or both the following

// non-const reference to the member
std::vector<std::shared_ptr<B>>& GetVec()
{
    return myVec_;
}

// const reference to the member
const std::vector<std::shared_ptr<B>>& GetVec() const /* noexcept */
{
    return myVec_;
}

Upvotes: 3

Related Questions