As noted in the comments, you cannot actually “move” anything from the argument object because it is const (at least not without casting const, which is a bad idea, as this can lead to UB). So this is clearly not useful for moving. The whole purpose of movement semantics is to provide performance optimization, and this does not happen here, so why do it?
However, I can only think of two cases where this is useful. The first includes greedy constructors:
#include <iostream> struct Foo { Foo() = default; Foo(const Foo&) { std::cerr << "copy constructor"; } Foo(Foo&&) { std::cerr << "copy constructor"; } template <class T> Foo(T&&) { std::cerr << "forward"; } }; const Foo bar() { return Foo{}; } int main() { Foo f2(bar()); return 0; }
This program prints "forward". The reason is that the computed type in the template will be const Foo , which makes it a better match. This also shows up when you have the perfect redirects to the variation constructors. Common for proxy objects. Of course, returning by const value is bad practice, but, strictly speaking, this is not true, and it could break your class. So you really have to provide an overload of Foo(const Foo&&) (which just delegates to the copy constructor); think of it as the intersection of t, or how I write high-quality generic code.
The second case arises if you want to explicitly remove the move constructors or the move transformation operator:
struct Baz { Baz() = default; Baz(const Baz&) = default; Baz(Baz&&) = delete; }; const Baz zwug() { return {}; } int main() { Baz b2(zwug()); }
This program compiles, so the author has not completed his task. The reason is that const ref overloads the match with const rvalues, and const rvalue has not been explicitly deleted. If you want to remove moves, you will also need to remove the const rvalue overload.
The second example may seem wildly obscure, but say that you are writing a class that provides a string representation. You may not want it to be created from a string, temporary, since you are at a greater risk of damaging the image.
Nir friedman
source share