簡體   English   中英

在模板中強制引用引用似乎消除了一致性

[英]Casting to reference in a template seems to cast away const-ness

考慮以下C ++代碼:

typedef std::string& mutable_string_ref;
const std::string str = "abc";
mutable_string_ref ref(str);

顯然,這會導致編譯器錯誤,因為您無法創建對const字符串的可變引用。 使用GCC 4.7.2時,產生的錯誤是:

error: invalid initialization of reference of type ‘mutable_string_ref {aka std::basic_string<char>&}’ from expression of type ‘const string {aka const std::basic_string<char>}’


但是 ...為什么我們嘗試相同的操作,只是將引用類型作為模板參數傳遞,突然似乎忽略了const-ness?

考慮:

template <class T>
T get()
{
    const static std::string s = "abc";
    return T(s);
}

int main()
{
    std::string& s = get<std::string&>();
    s = "blah"; // undefined behavior!!
}

上面的代碼在GCC 4.7.2上可以正常編譯,沒有警告。 我不明白為什么會編譯。 似乎表達式T(s)基本上被解釋為C型樣式轉換,只是舍棄了const-ness。 但為什么? 我用T = std::string&實例化了函數模板get ,所以表達式return T(s)應該無法編譯,因為sconst 但是它並沒有失敗。

Ideone鏈接: http ://ideone.com/TAO5C6

這是編譯器錯誤嗎? 還是有一些合理的理由可以編譯?

您不是在初始化,而是C樣式轉換,它確實具有消除常量性的能力。

從標准:

5.2.3顯式類型轉換(功能符號)[expr.type.conv]

1簡單類型說明符(7.1.6.2)或類型名說明符(14.6)后跟帶括號的表達式列表,可在給定表達式列表的情況下構造指定類型的值。 如果表達式列表是單個表達式,則類型轉換表達式(在定義上以及含義上)與相應的強制轉換表達式(5.4)等效。

5.4顯式類型轉換(強制轉換符號)

1表達式(T)的結果強制轉換為類型T [...]

暫無
暫無

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

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