This is an undefined behaviour, because temporary Bar
object will be destroyed at ;
.
Foo Bar::Copy()
{
return Bar();
}
is safer. BUT thanks to @Cat Plus Plus and @celtschk, I realized that this method leads to slicing, losing the all Bar
specific information. In order to keep the Bar
object Copy()
must return either a reference or a pointer to the object. Here we are at the beginning again as this is UB. So Bar
must be allocated dynamically instead, that its reference/pointer lives at the out of Copy()
function. Who should be responsible for deleting this dynamically generated Bar
object?
#include <memory>
std::shared_ptr<Foo> Bar::Copy()
{
return std::shared_ptr(new Bar());
}
shared_ptr
will do this automatically for you.