当以下代码由 g++ 或 clang++ 编译时,我收到警告“返回对临时对象的引用”(g++)和“返回对本地临时对象的引用”(clang++)。
有人能告诉我为什么会getData_warning
出现这些警告,而getData_nowarning
没有吗?
struct Geom {
int * data;
};
// Not ideal because one can change the pointed to value
int * const & getData_nowarning (Geom const & geom) {
return geom.data;
}
// Ideal because one cannot change the pointed to value.
int const * const & getData_warning (Geom const & geom) {
return geom.data; // <------------------- WARNING HERE
}
void test () {
Geom const geom = { new int(0) };
int * data1 = getData_nowarning(geom);
int const * data2 = getData_warning(geom);
}