To my understanding, when a vector increases its capacity, it allocates a new memory, copy(move?) all contents to the new array, and then destroy the old one:
vector<int> v;
v.emplace_back(1);
v.emplace_back(2); cout<<&v[0]<<endl; // outputs 0x4b16d0
v.emplace_back(3); cout<<&v[0]<<endl; // outputs 0x4b16f0
+-----+
0x4b16d0 | 1 2 |
+-----+
+---------+
0x4b16f0 | 1 2 3 |
+---------+
In above example, how 1 and 2 move
from 0x4b16d0
to 0x4b16f0
?
Updated with user-defined class
struct foo {
foo() {}
foo(const foo &) { cout << "copy\n"; }
foo(foo &&) noexcept { cout << "move\n"; }
};
int main() {
vector<foo> v;
cout<<"1st emplace_back() \n"; v.emplace_back(); cout<<" addr of 1st element: "<<&v[0]<<endl;
cout<<"2nd emplace_back() \n"; v.emplace_back(); cout<<" addr of 1st element: "<<&v[0]<<endl;
}
$ g++ -std=c++11 -g a.cpp; ./a.exe
1st emplace_back()
addr of 1st element: 0x6f16d1
2nd emplace_back()
move
addr of 1st element: 0x6f16f1
My question is, even the move
ctor is called, it still copies data from one place to another, is that right?
If so, does that mean it doesn't improve performance at all when vector increase its capacity using move semantics?