Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function which returns a reference to local object

I've written a function which returns a reference to local object.

Fraction& operator*(Fraction& lhs, Fraction& rhs)
{
    Fraction res(lhs.num*rhs.num,lhs.den*rhs.den);
    return res;
}

After function return the res object will be destroyed and receiving object will point to Ex-Fraction object leading to undefined behavior on using it. Anybody who is going to use this function will face problem.

Why does compiler can't detect this kind of situation as compile time error ?

like image 259
shivakumar Avatar asked Jun 11 '13 14:06

shivakumar


1 Answers

Most compilers will show a warning when you do that. You should always turn warnings on with an option such as GCC's -Wall.

As for why an error isn't required by the Standard, it's because a function with flow control will make it difficult to tell whether the return value is referencing a local or not. (And undefined behavior only occurs if the return value is used by the caller.)

like image 93
Potatoswatter Avatar answered Sep 23 '22 09:09

Potatoswatter