我目前正试图通过这篇文章了解复制和交换习语.发布的答案中包含以下代码
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
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
我注意到作者使用了这个陈述
swap(*this, other);
Run Code Online (Sandbox Code Playgroud)
other是临时的或者rvalue是作为方法交换的引用传递的.我不确定我们是否可以通过引用传递右值.为了测试这个,我尝试这样做,但是直到我将参数转换为a后,以下操作才起作用const reference
void myfunct(std::string& f)
{
std::cout << "Hello";
}
int main()
{
myfunct(std::string("dsdsd"));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何other暂时通过引用传递, swap(*this, other);而myfunct(std::string("dsdsd"));不能通过引用传递.
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |