2017-03-31 51 views
3

我需要從函數返回一個const引用。此代碼的東西:const在帶有尾隨返回類型的自動返回聲明中意味着什麼?

auto test()->add_lvalue_reference<const int>::type 
{ 
    static int i{50}; 
    return i; 
} 

int & i{test()}; // doesn't compile 

但這個片段中,看起來痛苦相似,給出了一個不正確的結果:

auto const test()->add_lvalue_reference<int>::type 
{ 
    static int i{50}; 
    return i; 
} 

int & i{test()}; // compiles thougth test() returned a const 

我從類型聲明回報聲明移動關鍵字const

起初,我以爲,是扣除函數簽名在第二種情況下變成了:

int & const test(); // not valid - const qualifiers cannot be applied to int& 

這不是一個有效的C++。但用auto說明符編譯。

所以我的問題是const是什麼意思在函數返回類型與自動追尾返回?或者它被丟棄了?

+3

恭喜,您發現了一個編譯器錯誤。 –

回答

5
auto const test()->add_lvalue_reference<int>::type 

這是形成不良的,見[dcl.fct]/2(在一個尾返回型被使用的情況下,「T應爲單類型說明符auto」)。

+0

你說得對。我需要先在不同的編譯器上測試。 Clang和msvc拒絕與gcc相反編譯。 – nikitablack