I know there are a ton of questions asking something similar, but I couldn't find anything for my exact situation (operator overload, pass by copy).
As far as I know, returning a reference to a local variable and then using it should result in undefined behaviour. But it seems to be working in my case. Is it simply a case of undefined behaviour can also mean it will work sometimes, or am I overlooking something?
// complex.cc
Complex& operator/(Complex lhs, const Complex& rhs)
{
return lhs /= rhs;
}
// inside main
complex::Complex a{3, -6};
complex::Complex b{1, -5};
complex::Complex res{a / b};
std::cout << a << '\n' << b << '\n' << res << std::endl;
As I understand it, shouldn't there be a copy of a
created, when I pass it to the overloaded operator, which then returns a reference to the modified copy? Is that understanding wrong, or why does it work when I print it?