Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does returning a reference to a local variable work in this case?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?

You are not. The behavior is undefined, which means that it may look like it’s working.

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?

That’s also correct – and the copy goes out of scope when the function returns so the returned reference is a dangling reference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading