为什么我得到 "warning: returning reference to local temporary object"?

Why am I getting "warning: returning reference to local temporary object"?

我在下面的代码中从 clang 编译器得到 warning: returning reference to local temporary object,我不确定为什么。 (code on 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 问题,但其中大多数都有一个 getter return 是函数或方法的临时值。但是,我不确定为什么上面的代码也是如此?

我想 return 仅出于阅读目的对内部私有成员进行 const 引用。

那是因为 SpecialIdOtherIduint32_t,并且由于你的函数 returns int 它必须隐式转换所以一个临时的已创建。

要么将 Full_Coord::rFull_Coord::ls 的 return 类型分别更改为 SpecialIdOtherId,或者使用 auto 作为 return类型。

auto const& r() const { return xy_r.r(); }
auto const& ls() const { return ls_; }