dimanche 26 septembre 2021

Is this proper usage of smart pointers C++

I was wondering if the following is correct usage of a shared pointer. 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 shared ptr on main and move ownership using the AddToVec function?

Aucun commentaire:

Enregistrer un commentaire