简体   繁体   English

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

[英]How can I avoid dynamic allocation when I need polymorphism?

With GCC on Ubuntu 14.04 and the following MCVE: 在Ubuntu 14.04上使用GCC和以下MCVE:

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 is derived from TargetInterface and targetInterface is dynamically allocated in main() . FlashTarget派生自TargetInterfacetargetInterfacemain()动态分配。

Is there a way to avoid dynamic allocation for the above code? 有没有办法避免上述代码的动态分配

This would be the naive answer: 这将是天真的答案:

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

Note: with this approach, you must ensure that target will live as long as targetInterface is used. 注意:使用此方法,只要使用targetInterface必须确保target将存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM