问题
Here is my test code:
void test(std::vector<int> vec){};
void test(std::vector<int> && vec){};
int main(int argc, char * argv[])
{
std::vector<int> v;
test(v);
test(std::move(v));
return 0;
}
When I try to call test(std::move(v))
, I was told test
is multiply implemented. Obviously I have used std::move making v
a rvalue. Won't test(std::vector<int> &&)
be called specifically?
回答1:
This isn't directly related to rvalues, or moving. The same happens with an lvalue reference overload
void test(std::vector<int> vec){};
void test(std::vector<int> & vec){};
int main(int argc, char * argv[])
{
std::vector<int> v;
test(v); // ambiguous
return 0;
}
The implicit conversion sequences of the two overloads are equivalent. The reason your example only flares up on a move is that the first call passes an lvalue (making the second overload not applicable), while applying std::move
again produces two equivalent conversion sequences.
Accepting a parameter by value means the argument can be initialized by either a move or a copy. So if you have another overload on a reference (be it rvalue or lvalue), there is going to be an ambiguity for that value category.
来源:https://stackoverflow.com/questions/53627939/multiple-implementation-caused-by-rvalue-parameter