I have something like this:
struct D {
virtual void operator() {...};
}
struct D1 : public D {
virtual void operator() {...};
}
struct D2 : public D {
virtual void operator() {...};
}
void foo(D &d) {...};
And so this is fine, and nicely controls the life cycle of my D’s:
foo(D());
foo(D1());
foo(D2());
But I choose my D variant in multiple places, so I want a simple factory:
const D& make_D()
{
// BAD, returning reference to temporary
if(is_tuesday())
return D1();
return D2();
}
Instead of returning a reference to a temporary, I could return an object, but then I slice to the base class. Alternatively, I could return a pointer from my factory, but then the client has to delete it. Other, more complicated, solutions also impose more load on the client.
Is there a way to write something like
D& d = make_D();
foo(d);
(or even foo(make_D()))? The goal is to wrap the complexity in the various D definitions and in make_D() so that the functions like foo() and those who call those functions needn’t worry about it.
The usual way is to either return a pointer or a smart pointer.
The downside of using a pointer is letting the user manage its memory.
If you return a smart pointer, this is no longer an issue.