Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to return a literal by const reference?

Tags:

c++

Is this safe?

const int& f()
{
return 1;
}

What I'm trying to do is to return a some value to const &

like image 561
smallB Avatar asked Feb 02 '23 15:02

smallB


2 Answers

It is not okay.
Returning reference to a temporary is not okay because accessing it outside the function causes Undefined Behavior.

like image 55
Alok Save Avatar answered Feb 05 '23 05:02

Alok Save


No, you're returning a reference to a temporary variable - this is not safe. The temporary variable will have been destroyed upon function return.

like image 33
sharptooth Avatar answered Feb 05 '23 05:02

sharptooth