I’m not sure if the question title is accurate… Let me start by explaining my original simple scenario, and then move on to explain what would I like to do, but can’t.
Originally, I had something like:
class Operand;
Operand genOperandA() { ...; return Operand(); }
Operand genOperandB() { ...; return Operand(); }
... // more operand-generation functions
typedef Operand (*OpGen)();
// Table of function pointers
static const OpGen generators[] =
{
genOperandA,
genOperandB,
...
};
// Function to do some operation on the operand
void operate(Operand& op);
...
// Example call
operate(generators[1]());
So far so good (I think). However, there are now several derived operand types, e.g. class RegisterOperand : public Operand. I have new, dedicated genOperand functions that ideally would return instances of the derived types. But I can’t do this:
Operand genOperandC() { ...; return RegisterOperand(); }
and I can’t do this:
RegisterOperand genOperandC() { ...; return RegisterOperand(); }
static const OpGen generators[] =
{
...
genOperandC,
};
However, I know this would work if I were to return reference or pointer types, so the only option I currently have is something like:
Operand *genOperandC() { ...; return new RegisterOperand(); }
which now requires explicit cleanup which wasn’t necessary originally.
Any alternatives I haven’t considered?
There might be other designs that doesn’t require you to use pointers, but if you need or want to go this way, this might interest you.
If returning a pointer is a problem (because of the need to “clean-up” things), you definitely should consider using smart pointers as return type.
Here is an example of your factory method with smart pointers:
This way, you won’t have to call
deletemanually: it will be done by the destructor ofboost::shared_ptr<Operand>for you when required.If afterwards you need to cast the resulting pointer,
boostprovides casting functions as well: