KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Suppose I have the following code: class B { /* */ }; class A { vector<B*> vb; public: void add(B* b) { vb.push_back(b); } }; int main() { A a; B* b(new B()); a.add(b); } Suppose that in this case, all raw pointers B* can be handled through unique_ptr<B> . Surprisingly, I wasn't able to find how to convert this code using unique_ptr . After a few tries, I came up with the following code, which compiles: class A { vector<unique_ptr<B>> vb; public: void add(unique_ptr<B> b) { vb.push_back(move(b)); } }; int main() { A a; unique_ptr<B> b(new B()); a.add(move(b)); } So my simple question: is this the way to do it and in particular, is move(b) the only way to do it? (I was thinking of rvalue references but I don't fully understand them.) And if you have a link with complete explanations of move semantics, unique_ptr , etc. that I was not able to find, don't hesitate to share it. EDIT According to http://thbecker.net/articles/rvalue_references/section_01.html , my code seems to be OK. Actually, std::move is just syntactic sugar. With object x of class X, move(x) is just the same as: static_cast <X&&>(x) These 2 move functions are needed because casting to a rvalue reference: prevents function "add" from passing by value makes push_back use the default move constructor of B Apparently, I do not need the second std::move in my main() if I change my "add" function to pass by reference (ordinary lvalue ref). I would like some confirmation of all this, though...
Tags (comma-separated)
Save Edits
Cancel