我目前正试图通过这个post了解复制和交换习惯用法。发布的答案具有下面的代码在它通过临时作为参考
class dumb_array
{
public:
// ...
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
// move constructor
dumb_array(dumb_array&& other)
: dumb_array() // initialize via default constructor, C++11 only
{
swap(*this, other); //<------Question about this statement
}
// ...
};
我注意到,作者使用这个声明
swap(*this, other);
other
是一个临时的或正在被作为该方法交换一个引用传递一个rvalue
。我不确定是否可以通过引用传递一个右值。 为了测试这一点,我试着这样做但是下面没有工作,直到我的参数转换为const reference
void myfunct(std::string& f)
{
std::cout << "Hello";
}
int main()
{
myfunct(std::string("dsdsd"));
}
我的问题是如何能够other
被临时被引用在swap(*this, other);
传递而myfunct(std::string("dsdsd"));
不能是通过参考传递。
我认为你需要了解什么是右值引用是:http://stackoverflow.com/a/5481588/4342498 – NathanOliver 2015-03-31 19:08:28
swap(* this,other);'是错误的。它必须是'swap(* this,std :: move(other));'(其他是一个命名变量) – 2015-03-31 19:12:03
@DieterLücking在这种情况下,交换方法不会工作,因为它需要一个引用,并且你传递一个临时的。如果它是一个不变的参考,它只会按照你的建议工作。请纠正我,如果我错了 – Rajeshwar 2015-03-31 19:13:40