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.
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_; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With