Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move vs std::auto_ptr?

What can I do with 'move' (r-value references) in C++11 what I can't with std::auto_ptr? (As I understand they are different implementations of one idea.)

And old question again: is std::auto_ptr so bad component?

like image 444
Iakov Minochkin Avatar asked Dec 11 '11 16:12

Iakov Minochkin


1 Answers

C++98/03 has no notion of truly "movable" classes. auto_ptr is a class with transfer-on-copy-semantics, i.e. when you make a copy, the content of the original changes (note the copy constructor with non-const argument!). This is Bad. Such a class cannot be used in the standard containers.

C++11 introduces the concept of truly movable classes thanks the the newly added notion of rvalue references. The new unique_ptr, which replaces auto_ptr entirely, is no longer copyable at all, but instead it is movable. All standard containers have been updated to attempt to move objects if possible, so it is now possible to store move-only objects in standard containers. Other examples of object which are only movable but not copyable are mutexes, locks, threads and iostreams.

To hammer in the point, compare a hypothetical, broken, C++98 piece of code with the corresponding C++11 code:

std::auto_ptr<Foo> p1(new Foo);
std::vector< std::auto_ptr<Foo> > v1;
//v1.push_back(p1);  // eeww, what is the state of p1 now? ERROR

std::unique_ptr<Foo> p2(new Foo);
std::vector<std::unique_ptr<Foo>> v2;
//v2.push_back(p2);          // Error, copying is simply not allowed
v2.push_back(std::move(p2)); // explicit; mustn't read p2 after moving it
v2.emplace_back(new Foo);    // even better ;-)
like image 130
Kerrek SB Avatar answered Oct 03 '22 23:10

Kerrek SB