[英]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
派生自TargetInterface
, targetInterface
在main()
动态分配。
Is there a way to avoid dynamic allocation for the above code? 有没有办法避免上述代码的动态分配 ?
This would be the naive answer: 这将是天真的答案:
void main()
{
FlashTarget target;
targetInterface = ⌖
}
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.