【发布时间】:2015-11-16 13:34:42
【问题描述】:
Clang 编译器在编译此代码 sn-p 时产生警告,我不知道为什么。
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 在此代码上没有显示警告。
我可以像这样修复 sn-p:const auto p = Get();
但我想知道是否有一些临时对象并且问题更深层次
【问题讨论】:
-
@101010 “临时对象”?也许你可以更清楚一点?我们绝对可以在堆栈中引用非常量变量。
-
p是临时的,*p是有效的。我认为这是 Clang 的误报。 -
@JonathanMee: Learn about temporaries
-
@LightnessRacesinOrbit 这是一本很好的读物,现在我已经开始阅读了,谢谢。
标签: c++ reference return compiler-warnings clang++