Code: Select all
/*
(c) 2012 +++ Filip Stoklas, aka FipS, http://www.4FipS.com +++
THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
ARTICLE URL: http://forums.4fips.com/viewtopic.php?f=3&t=713
*/
#include <vector>
class Foo // non-copyable, movable
{
public:
Foo() : _data(64) {}
Foo(Foo&& rhs) : _data(std::move(rhs._data)) {} // move constructor
Foo& operator=(Foo&& rhs) { _data = std::move(rhs._data); return *this; } // move assignment
private:
Foo(const Foo&); // non-copyable ('= delete' in C++11)
Foo& operator=(const Foo&); // non-copyable ('= delete' in C++11)
std::vector<unsigned char> _data;
};
Foo load_foo()
{
Foo foo;
// ...
return foo; // returns an rvalue
}
int main()
{
Foo foo = load_foo(); // moves, steals data from 'foo' inside 'load_foo()'
//Foo foo2 = foo; // DOESN'T COMPILE!
Foo foo3 = std::move(foo); // moves, steals data from 'foo'
const Foo bar = load_foo(); // moves, steals data from 'foo' inside 'load_foo()'
//Foo bar2 = bar; // DOESN'T COMPILE!
//const Foo bar3 = std::move(bar); // // DOESN'T COMPILE!, can't steal from const 'bar'
return 0;
}