/** * compile and run with these commands: * * g++ -std=c++11 -fno-elide-constructors test-move.cpp * ./a.outmain() * * will output the following: fn() construct move move assignment delete. (data size = 0) move move assignment delete. (data size = 0) 1 2 3 4 5 delete. (data size = 5) * **/ #include #include using namespace std; class Object { public: Object() { clog << "construct\n"; // using initializer list: _data = {1,2,3,4,5}; } Object(Object& obj) : _data(obj._data) { clog << "copy\n"; } Object& operator=(Object& obj) { clog << "copy assignment\n"; _data = obj._data; return *this; } Object(Object&& obj) { clog << "move\n"; // this passes obj along to // the move assignment operator *this = move(obj); } Object& operator=(Object&& obj) { clog << "move assignment\n"; // all member variables must be // move individually _data = move(obj._data); return *this; } ~Object() { // delete. If _data.size() == 0, // we are merely deleting a reference // and no deallocation is taking place clog << "delete." << " (data size = " << _data.size() << ")\n"; } vector _data; }; Object fn() { clog << "fn()\n"; Object obj; return obj; } int main() { clog << "main()\n"; Object obj = fn(); // range-based for-loop and the auto keyword for (auto x : obj._data) { cout << x << endl; } }