As the comments have noted, you cannot actually "move" anything out of the argument object, because it is const (at least, not without a const cast, which is a bad idea as it could lead to UB). So it's clearly not useful for the sake of moving. The entire purpose of move semantics is to provide a performance optimization, and that is not happening here, so why do it?
That said, I can only think of two cases where this is useful. The first involves "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 why is because the deduced type in the template will be const Foo
, making it a better match. This also shows up when you have perfect forwarding variadic constructors. Common for proxy objects. Of course returning by const value is bad practice, but strictly speaking it's not incorrect, and this may break your class. So you should really provide a Foo(const Foo&&)
overload (which just delegates to the copy constructor); think of it as crossing a t or dotting an i when you are writing high quality generic code.
The second case occurs when you want to explicitly delete move constructors, or a move conversion 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 failed at their mission. The reason why is because const ref overloads match against const rvalues, and const rvalue construction was not explicitly deleted. If you want to delete moves you'll need to delete the const rvalue overload too.
The second example may seem wildly obscure but say you are writing a class that provides a view of a string. You may not want to allow it to be constructed from a string temporary, since you are at greater risk of the view being corrupted.