Reputation: 3397
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 ?
Upvotes: 9
Views: 764
Reputation: 137780
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.)
Upvotes: 19