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

Is returning a reference to a pointer in a class defined behaviour?

Consider

#include <iostream>

struct Foo
{
    int* n;
    Foo(){n = new int{};}
    ~Foo(){delete n;}
    int& get()
    {
        int* m = n;
        return *m;
    } 
};

int main()
{
    Foo f;
    std::cout << f.get();
}

This is a cut-down version of a class that manages a pointer, and has a method that returns a reference to the dereferenced pointer.

Is that defined behaviour?

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 :

Is that defined behaviour?

Yes, the given program is well-formed. You’re returning a non-const lvalue reference that refers to a dynamically allocated integer pointed by the pointer n and m. The integer object still exists after the call f.get(). That is, itis not a function local variable.


Note also that just returning a reference to a potentially local variable is not undefined behavior in itself. It’s just that if you were to use that returned reference(aka dangling reference) to a local variable that nolonger exists, then we will get UB.

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