Non-copyable, movable types in C++11

> Coding, hacking, computer graphics, game dev, and such...
User avatar
fips
Site Admin
Posts: 166
Joined: Wed Nov 12, 2008 9:49 pm
Location: Prague
Contact:

Non-copyable, movable types in C++11

Post by fips »

I've just started to take advantage of the move semantics that C++11 offers. What I find especially convenient is the fact that I'm now able to define Non-copyable, movable types. So it's finally possible to pass by value without the fear of copy overhead. This technique also significantly reduces the need for std::unique_ptr, which makes things even easier. See the example below to get the idea (it compiles under Visual Studio 2010):

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;
}