簡體   English   中英

將臨時綁定到左值引用

[英]Binding temporary to a lvalue reference

我有以下代碼

string three()
{
    return "three";
}

void mutate(string& ref)
{
}

int main()
{
    mutate(three()); 
    return 0;
}

你可以看到我正在傳遞三個()mutate方法。 這段代碼編譯得很好。 我的理解是,不能將臨時變量分配給非常量引用。 如果是,這個程序是如何編譯的?

有什么想法嗎?

編輯:

編譯器嘗試過:VS 2008 和 VS2010 Beta

它曾經在 VC6 編譯器中編譯,所以我想保持向后兼容性 VS2008 支持這個非標准擴展。 嘗試使用/Za (禁用語言擴展)標志,然后您應該會收到錯誤消息。

它是 VC++ 的邪惡擴展。 如果您使用 /W4 編譯,那么編譯器會警告您。 我猜您正在閱讀Rvalue References: C++0x Features in VC10, Part 2 這篇文章也提到了這個問題。

這是一個微軟擴展,模仿許多其他微軟編譯器的行為。 如果啟用 W4 警告,您將看到警告。

無法編譯,至少使用 g++ 4:

foo.cpp: In function ‘int main()’:
foo.cpp:16: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’
foo.cpp:10: error: in passing argument 1 of ‘void mutate(std::string&)’

(行號減少了 3 或 4,因為我必須添加 #include 和 'using' 行。)

因此,您的編譯器似乎沒有應有的嚴格。

我想這取決於編譯器。 g++ 4.1.2 給了我這個。

In function 'int main()':
Line 15: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::string'
compilation terminated due to -Wfatal-errors.

也許是因為您沒有做任何事情,所以呼叫被優化掉了。

暫無
暫無

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

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