簡體   English   中英

C ++,為什么可以將右值傳遞給以左值引用為參數的函數

[英]C++, why can you pass rvalue to a function which takes lvalue reference as argument

為什么可以將右值傳遞給需要引用的函數?

void func(const std::string& x)
{
    std::cout << x << std::endl;
}

int main()
{
    std::string& x = "Test"; //fails to compile
    func("Test"); //works
    return 0;
}

在嘗試之前,我認為我需要在調用func之前創建一個字符串變量。

std::string tmp = "Test";
func(tmp);

就像我需要創建參考一樣。

std::string tmp = "Test";
std::string& x = tmp;

這與傳遞給函數無關,而與對const對象的lvalue引用有關。

std::string& x = "Test"; //fails to compile

以上嘗試將臨時綁定到非常量引用。 如果我們要對其進行調整,它將格式正確:

std::string const& x = "Test"; // compiles

現在,它可以延長臨時文件的壽命,直到引用超出c ++標准要求的范圍。
知道了這一點,我們可以通過將原型更改為以下內容來使您的函數無法編譯:

void func(std::string& x)

現在,functions參數無法綁定到臨時對象,因為它由非const引用接受。


對於后c ++ 11時代,事情會變得更加有趣。 您可以將臨時綁定到非常量rvalue引用:

std::string&& x = "Test"; //Okay and still extends the lifetime of the temporary

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM