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/) –