O'Reilly logo

Boost C++ Application Development Cookbook by Antony Polukhin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Making a noncopyable but movable class

Now imagine the following situation: we have a resource that cannot be copied, which should be correctly freed in a destructor, and we want to return it from a function:

descriptor_owner construct_descriptor() {
    return descriptor_owner("Construct using this string");
}

Actually, you can work around such situations using the swap method:

void construct_descriptor1(descriptor_owner& ret) {
    descriptor_owner("Construct using this string").swap(ret);
}

But such a workaround won't allow us to use descriptor_owner in STL or Boost containers. And by the way, it looks awful!

Getting ready

It is highly recommended to know at least the basics of C++11 rvalue references. Reading the Using the C++11 move emulation recipe is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required