I was reading a book about data structure implemented in C++, I dont understand a code snippet, it's part of vector class
void push_back(object &&x) {
//do something
objects[size++] = std::move(x);
}
I know that std::move
return a rvalue reference of the object, but the push_back
member function already has rvalue reference x
as parameter, isn't the std::move
here unnecessary?
Another question is if we have a rvalue reference of a class object, we still need to use std::move
on its member if we want to call move instead of copy right? like the code below:
A& operator=(A&& other) {
member = std::move(other.member);
return *this;
}
objects[size++] = std::move(x);
requires a valid object of vector's value type at&objects[size]
, which is not howpush_back
should work. Vectors typically use placement new (allocator'sconstruct
generally) to create a new object there, not an assignment operator. Also note that if the assignment throws (by throwing move assignment op. or copy assignment op.), then, thesize
will be incremented and the state of the vector will be incorrect. Better to dosize++;
at the next line. – Fief