为什么我收到“警告:返回对本地临时对象的引用”?

Dan*_*iel 4 c++ c++14

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::rFull_Coord::lsSpecialIdOtherId分别或使用auto作为返回类型。

auto const& r() const { return xy_r.r(); }
auto const& ls() const { return ls_; }
Run Code Online (Sandbox Code Playgroud)

  • 完全合适。这是给未来使用旧工具尝试此操作的读者的注释。我的意思是蓝精灵。我们仍然收到有关 Turbo C++ 的问题。 (4认同)