簡體   English   中英

C ++了解默認參數中的參考

[英]C++ understand reference in default parameter

我對C ++中默認參數的引用有疑問。

SWindows(const std::string&, int, const std::string& flag = "UDP");SWindows(const std::string&, int, const std::string& flag = "UDP");

我不明白為什么要編譯此代碼(IDE Visual Studio 2012)。 對我來說,引用是對象別名。 因此,我們無法聲明此行。 假定“標志”已經存在。

因此,這是編譯器優化還是誤解?

const左值可以綁定到臨時對象。 就這樣。 因此,該代碼是合法且格式正確的。

只要存在flag ,該臨時對象的生存期就會延長。 不必說,您不能將臨時對象綁定到非常量左值引用。

您可以使用const引用做到這一點。 您還可以將rvalues與const引用一起使用,例如:

void SomeFunction(SomeObject const& s)
 { ... };

然后你可以打電話

SomeFunction(SomeObject());

您之所以這樣做,是因為通過說出它的const引用,您可以知道您不會修改所引用的變量。 如果不是const& ,則無法執行該操作。

了解代碼

SWindows(const std::string&, int, const std::string& flag = "UDP");

您應該將其分為兩部分。

SWindows(const std::string&, int, const std::string& flag );

SWindows( SomeString, SomeInt, "UDP" );

由於“ UDP”的類型不是std :: string,因此通過調用接受字符串文字作為其第一個參數的構造函數,將其隱式轉換為std :: string類型的對象。 所以最后一條語句等於

SWindows( SomeString, SomeInt, std::string( "UDP" ) );

表達式std :: string(“ UDP”的結果是一個臨時對象,您可以將其綁定到const引用。因此const引用是該臨時對象的別名,

您可以想象這樣一種方式,即在函數體內有定義

const std::string &flag = std::string( "UDP" );

暫無
暫無

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

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