2015-03-31 86 views
0

我目前正试图通过这个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"));不能是通过参考传递。

+1

我认为你需要了解什么是右值引用是:http://stackoverflow.com/a/5481588/4342498 – NathanOliver 2015-03-31 19:08:28

+1

swap(* this,other);'是错误的。它必须是'swap(* this,std :: move(other));'(其他是一个命名变量) – 2015-03-31 19:12:03

+0

@DieterLücking在这种情况下,交换方法不会工作,因为它需要一个引用,并且你传递一个临时的。如果它是一个不变的参考,它只会按照你的建议工作。请纠正我,如果我错了 – Rajeshwar 2015-03-31 19:13:40

回答

7

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

+0

是的,这是有道理的。所以其他基本上有一个右值,但本身就是一个左值。我对么 ? – Rajeshwar 2015-03-31 19:10:17

+0

@Rajeshwar:我认为引用是一个左值是稍微更准确的,因为左值是从右值构造的。 (引用不是真正的“构建”,但你明白了) – 2015-03-31 19:41:08

+0

感谢您清除 – Rajeshwar 2015-03-31 19:52:07

0

在的情况下:

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

std::string("dsdsd")是一个范围在调用myfunct()实际上是外内的暂时的。

C++明确指定将引用绑定到const会将临时的生命周期延长到引用本身的生命周期。