Reputation: 17110
Is this safe?
const int& f()
{
return 1;
}
What I'm trying to do is to return a some value to const &
Upvotes: 9
Views: 789
Reputation: 206518
It is not okay.
Returning reference to a temporary is not okay because accessing it outside the function causes Undefined Behavior.
Upvotes: 10
Reputation: 170489
No, you're returning a reference to a temporary variable - this is not safe. The temporary variable will have been destroyed upon function return.
Upvotes: 2