Clang編譯器生成警告編譯此代碼段,我找不出原因。指針解引用返回引用本地臨時對象
const int* Get() {
static const int ARRAY[4] = {1, 2, 3, 4};
return &ARRAY[0];
}
const int& Test() {
const auto& p = Get();
return (*p);
}
warning: returning reference to local temporary object [-Wreturn-stack-address]
return (*p);
GCC在此代碼上未顯示警告。 我可以解決這樣的片段:const auto p = Get();
但我想知道是否有一些臨時的對象,問題在於更深
@ 101010「臨時對象」?也許你可以更清楚一點?我們絕對可以引用堆棧中的非const變量。 –
鑑於'p'是一個臨時的,'* p'是有效的。我認爲這是Clang的誤判。 – Jarod42
@JonathanMee:[瞭解臨時工](http://herbsutter.com/2013/05/13/gotw-2-solution-temporary-objects/) –