簡體   English   中英

為什么我收到“警告:返回對本地臨時對象的引用”?

[英]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 返回給內部私有成員。

那是因為SpecialIdOtherIduint32_t ,並且由於您的 function 返回int它必須隱式轉換以便創建一個臨時的。

要么將Full_Coord::rFull_Coord::ls的返回類型分別更改為SpecialIdOtherId ,要么使用auto作為返回類型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM