[英]Why am I getting "warning: returning reference to local temporary object"?
我收到warning: returning reference to local temporary object
,我不確定為什么。 ( gdbolt 上的代碼)
<source>: In member function 'const int& Full_Coord::r() const':
<source>:29:41: warning: returning reference to temporary [-Wreturn-local-addr]
29 | int const& r() const { return xy_r.r(); }
| ~~~~~~^~
<source>: In member function 'const int& Full_Coord::ls() const':
<source>:30:36: warning: returning reference to temporary [-Wreturn-local-addr]
30 | int const& ls() const { return ls_; }
| ^~~
Execution build compiler returned: 0
Program returned: 0
#include <iostream>
using SpecialId = uint32_t;
using OtherId = uint32_t;
class Point2D {
public:
constexpr Point2D(double x, double y, SpecialId r) noexcept:
x_(x), y_(y), r_(r){}
double const& x() const { return x_; }
double const& y() const { return y_; }
SpecialId const& r() const { return r_; }
private:
double x_;
double y_;
const SpecialId r_;
};
class Full_Coord {
public:
constexpr Full_Coord(double x, double y, SpecialId r, OtherId ls) noexcept:
xy_r(x, y, r), ls_(ls) {}
int const& r() const { return xy_r.r(); }
int const& ls() const { return ls_; }
private:
const Point2D xy_r;
const OtherId ls_;
};
int main(){
Full_Coord full{1, 2, 3, 4};
auto const& my_r = full.r();
return 0;
}
我試過閱讀與此相關的其他 SO 問題,但其中大多數都有一個從 function 或方法返回臨時值的吸氣劑。 但是,我不確定為什么上面的代碼也是如此?
我只想出於閱讀目的將 const ref 返回給內部私有成員。
那是因為SpecialId
和OtherId
是uint32_t
,並且由於您的 function 返回int
它必須隱式轉換以便創建一個臨時的。
要么將Full_Coord::r
和Full_Coord::ls
的返回類型分別更改為SpecialId
和OtherId
,要么使用auto
作為返回類型。
auto const& r() const { return xy_r.r(); }
auto const& ls() const { return ls_; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.