smallB
smallB

Reputation: 17110

Is it OK to return a literal by const reference?

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

Answers (2)

Alok Save
Alok Save

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

sharptooth
sharptooth

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

Related Questions