In the following code, the getObj()
function returns a reference to a local object. This is obviously very bad since the object gets destroyed when the function returns (the ctor and dtor outputs emphasize the objects lifetime). As expected, the compiler (gcc44) gives a respective warning.
#include <iostream>
class Blah {
private:
int a_;
public:
Blah(int a) : a_(a) { std::cout << "Constructing...\n"; }
~Blah() { std::cout << "...Destructing\n"; }
void print() { std::cout << a_ << "\n"; }
};
Blah& getObj()
{
Blah blah(3);
return blah; // returning reference to local object
}
int main()
{
Blah& b = getObj();
b.print(); // why does this still output the correct value???
return 0;
}
However, calling print()
on the apparently destroyed object still prints the correct value of the private variable a_
. This is the output:
Constructing...
...Destructing
3
How can this be? I would have expected all of the objects data to be destroyed as well.