#include <stdio.h>
class Bar
{
public:
Bar() { printf ("Bar::Bar\n"); }
~Bar() { printf ("Bar::~Bar\n"); }
Bar(const Bar&) { printf("Bar::Bar(const Bar&)\n"); }
void baz() const { printf("Bar::Baz\n"); }
};
class Foo
{
Bar bar;
public:
Bar& getBar () { return bar; }
Foo() { }
};
int main()
{
printf("This is safe:\n");
{
Foo *x = new Foo();
const Bar y = x->getBar();
delete x;
y.baz();
}
printf("\nThis is a disaster:\n");
{
Foo *x = new Foo();
const Bar& y = x->getBar();
delete x;
y.baz();
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgpjbGFzcyBCYXIKewogICAgcHVibGljOgogICAgQmFyKCkgeyBwcmludGYgKCJCYXI6OkJhclxuIik7IH0KICAgIH5CYXIoKSB7IHByaW50ZiAoIkJhcjo6fkJhclxuIik7IH0KICAgIEJhcihjb25zdCBCYXImKSB7IHByaW50ZigiQmFyOjpCYXIoY29uc3QgQmFyJilcbiIpOyB9CiAgICB2b2lkIGJheigpIGNvbnN0IHsgcHJpbnRmKCJCYXI6OkJhelxuIik7IH0KfTsKCmNsYXNzIEZvbwp7CiAgICBCYXIgYmFyOwoKICAgIHB1YmxpYzoKICAgIEJhciYgZ2V0QmFyICgpIHsgcmV0dXJuIGJhcjsgfQogICAgRm9vKCkgeyB9Cn07CgppbnQgbWFpbigpCnsKICAgIHByaW50ZigiVGhpcyBpcyBzYWZlOlxuIik7CiAgICB7CiAgICAgICAgRm9vICp4ID0gbmV3IEZvbygpOwogICAgICAgIGNvbnN0IEJhciB5ID0geC0+Z2V0QmFyKCk7CiAgICAgICAgZGVsZXRlIHg7CiAgICAgICAgeS5iYXooKTsKICAgIH0KICAgIHByaW50ZigiXG5UaGlzIGlzIGEgZGlzYXN0ZXI6XG4iKTsKICAgIHsKICAgICAgICBGb28gKnggPSBuZXcgRm9vKCk7CiAgICAgICAgY29uc3QgQmFyJiB5ID0geC0+Z2V0QmFyKCk7CiAgICAgICAgZGVsZXRlIHg7CiAgICAgICAgeS5iYXooKTsKICAgIH0KICAgIHJldHVybiAwOwp9Cg==