Let\'s say I have some function:
Foo GetFoo(..)
{
...
}
Assume that we neither know how this function is implemented nor the internals of
These have semantic differences and if you ask for something other than you want, you will be in trouble if you get it. Consider this code:
#include
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;
}
Output is:
This is safe:
Bar::Bar
Bar::Bar(const Bar&)
Bar::~Bar
Bar::Baz
Bar::~BarThis is a disaster:
Bar::Bar
Bar::~Bar
Bar::Baz
Notice we call Bar::Baz
after the Bar
is destroyed. Oops.
Ask for what you want, that way you're not screwed if you get what you ask for.