当我需要多态性时,如何避免动态分配?

How can I avoid dynamic allocation when I need polymorphism?

在 Ubuntu 14.04 和以下 MCVE 上使用 GCC:

class TargetInterface
{
public:
   ~TargetInterface();
   //
   DataBuffer retDataBuffer();
   // following methods are all pure virtual
   virtual void delay() = 0;
   // ...
protected:   
   DataBuffer dataBuffer;
}

class FlashTarget : public TargetInterface
{
   public:
   void delay() override;
   // ...
}   

// globals
TargetInterface * targetInterface;

void main()
{
    targetInterface = new FlashTarget; // <--
    // ...
    // etc.
}

FlashTarget派生自TargetInterfacetargetInterfacemain()中动态分配。

有没有办法避免上述代码的动态分配

这将是天真的答案:

void main()
{
    FlashTarget target;
    targetInterface = &target;
}

注意:使用这种方法,您必须确保target只要使用targetInterface就可以存活。