我warning: returning reference to local temporary object从下面的代码中得到了 clang 编译器,但我不知道为什么。(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
Run Code Online (Sandbox Code Playgroud)
<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
Run Code Online (Sandbox Code Playgroud)
我已经尝试阅读与此相关的其他 SO 问题,但其中大多数都有一个 getter,可以从函数或方法返回临时值。但是,我不确定为什么在上面的代码中也是这种情况?
我想仅出于阅读目的将 const ref 返回给内部私有成员。
s d*_*s d 14
那是因为SpecialIdand OtherIdare uint32_t,并且由于您的函数返回int它必须隐式强制转换,因此会创建一个临时对象。
要么改变的返回类型Full_Coord::r和Full_Coord::ls到SpecialId和OtherId分别或使用auto作为返回类型。
auto const& r() const { return xy_r.r(); }
auto const& ls() const { return ls_; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |