Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++14

I'm getting warning: returning reference to local temporary object from clang compiler on code bellow and I'm not sure why. (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;
}

I've tried reading other SO questions related to this but most of them have a getter that returns a temporary from the function or a method. However, I'm not sure why is this also the case in the code above?

I wanted to return const ref to inner private members only for reading purposes.

like image 298
Daniel Avatar asked Dec 07 '22 10:12

Daniel


1 Answers

That is because the SpecialId and OtherId are uint32_t, and since your function returns int it must be implicitly cast so a temporary is created.

Either change the return types of Full_Coord::r and Full_Coord::ls to SpecialId and OtherId respectively, or use auto as a return type.

auto const& r() const { return xy_r.r(); }
auto const& ls() const { return ls_; }
like image 104
s d Avatar answered May 19 '23 18:05

s d