【发布时间】:2013-04-18 22:51:14
【问题描述】:
当以下代码由 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);
}
【问题讨论】:
标签: c++ reference constants temporary