假设我有这样的代码
template <typename T> void Swap(T&& a, T&& b) {
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
int main()
{
int a = 2;
int b = 3;
}根据我对this talk的理解,在调用Swap(a, b)时,编译器应该推断出T&&应该为T&,并对其进行转换。但在这种情况下,GCC给了我以下错误:
error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'std::remove_reference<int&>::type {aka int}'
T tmp = std::move(a);我要么必须使用Swap(std::forward<int>(a), std::forward<int>(b))或Swap(std::move(a), std::move(b))调用Swap,要么将Swap签名替换为Swap(T& a, T& b)。
为什么会这样呢?这里的正确用法是什么?
https://stackoverflow.com/questions/38379307
复制相似问题