将临时作为引用传递

Passing a temporary as a reference

本文关键字:引用      更新时间:2023-10-16

我目前正试图通过这篇文章来理解复制和交换习惯用法。张贴的答案中有以下代码

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);

CCD_ 1是作为对方法交换的引用而传递的临时或CCD_。我不确定我们是否可以通过引用传递右值。为了测试这一点,我尝试了这样做,但以下操作不起作用,直到我将参数转换为const reference

void myfunct(std::string& f)
{
    std::cout << "Hello";
}
int main() 
{
   myfunct(std::string("dsdsd"));
}

我的问题是,other作为一个临时的swap(*this, other);如何通过引用传递,而myfunct(std::string("dsdsd"));不能通过引用传递。

构造函数采用右值引用,但other是一个左值(它有一个名称)。

在的情况下

myfunct(std::string("dsdsd"));

std::string("dsdsd")是对myfunct()的调用实际上不在其范围内的临时值。

C++明确指定将引用绑定到const将临时的生存期扩展到引用本身的生存期。