[英]Returning reference to temporary, const differences
當以下代碼由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);
}
因為geom.data
的類型是int*
,所以不能通過引用int const*
來引用它。 為了引用int const*
,首先需要一個int const*
。 因此必須進行轉換,因此必須創建新類型的新指針,因此它必須是臨時的。
您是否需要函數的調用者才能更改geom對象中的指針指向的內容? 它似乎不是,因為你正在使指針本身為const。 所以只需刪除引用,就可以保留const。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.