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?
CodePudding user response:
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.