1. 4FipS.com
  2. Photos
  3. Videos
  4. Code
  5. Forums
  6. pfQuizzz
  7. About

4FipS.com Forums

Forums dedicated to the projects hosted at 4FipS.com

Skip to content

Non-copyable, movable types in C++11

> About coding, hacking, photography, and such...

Non-copyable, movable types in C++11

Postby FipS on Mon Apr 09, 2012 4:03 pm

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;
}
User avatar
FipS
Site Admin
 
Posts: 146
Joined: Wed Nov 12, 2008 9:49 pm
Location: Prague

Non-copyable, movable types in C++11

Sponsor

Sponsor
 

Return to 4FipS.com General Discussion & Blog

Who is online

Users browsing this forum: Bing [Bot], Google Adsense [Bot] and 1 guest

cron