1

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?
6
  • 2
    The std::move() isn't necessary. Commented Sep 26, 2021 at 14:28
  • 2
    Returning a vector of shared_prr by value is rather expensive. Commented Sep 26, 2021 at 14:33
  • 3
    @πάνταῥεῖ necessary for that? For successful compilation? Yes, the copy will suffice, but it simply does different things when we apply the move and when we don't. Commented Sep 26, 2021 at 14:35
  • @Fureeish could that be optimized using void AddToVec(std::shared_ptr<B>&& b)? Commented Sep 26, 2021 at 14:37
  • @πάνταῥεῖ - But that would make the move necessary. A value parameter is a sink for whatever value category. Commented Sep 26, 2021 at 14:40

1 Answer 1

3

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_; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.