I would like to do something like the following:
class Foo
{
Foo(int &&a, int b, std::string s="");
// does not compile because a is not an rvalue:
// Foo(int &&a, std::string s) : Foo(a, 0, s) {}
Foo(int &&a, std::string s) : Foo(std::move(a), 0, s) {} // move a
}
Edited based on comments
To clarify, I'm new to move semantics (and an amateur programmer) and I'm simply not sure if this is a good way to handle this situation.
I added the first question based on a comment (now deleted) that suggested this is not the correct way to overload constructors.
Is this a valid way to overload a constructor in general?
And specifically one that takes an rvalue reference as a parameter?
It is valid to overload constructors in general, even ones that have rvalue reference arguments.
In particular, your example is ill-formed. As you point out in the comments, the example fails to compile. To fix it, you must pass an rvalue to the constructor that you delegate to. The correct way to convert a rvalue reference variable into an rvalue is to use std::move
. So, what you must do is what you already know:
The only option I can see is to
std::move(a)
.