C++ 当我需要多态性时,如何避免动态分配?
使用Ubuntu 14.04上的GCC和以下MCVE:C++ 当我需要多态性时,如何避免动态分配?,c++,dynamic-memory-allocation,C++,Dynamic Memory Allocation,使用Ubuntu 14.04上的GCC和以下MCVE: class TargetInterface { public: ~TargetInterface(); // DataBuffer retDataBuffer(); // following methods are all pure virtual virtual void delay() = 0; // ... protected: DataBuffer dataBuffer; } cla
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.
}
类目标接口
{
公众:
~TargetInterface();
//
DataBuffer retDataBuffer();
//以下方法都是纯虚拟的
虚空延迟()=0;
// ...
受保护的:
数据缓冲;
}
类FlashTarget:公共TargetInterface
{
公众:
无效延迟()覆盖;
// ...
}
//全球的
TargetInterface*TargetInterface;
void main()
{
targetInterface=newFlashTarget;//这将是一个天真的答案:
void main()
{
FlashTarget target;
targetInterface = ⌖
}
注意:使用这种方法,您必须确保target
在使用targetInterface
的情况下仍然有效。将FlashTarget
对象放在堆栈上(或作为全局对象;我宁愿完全避免全局对象,但如果您真的想这样做的话…).你为什么认为你不能这么做?这是一个?void main()
不是标准的原型。@BoBTFish:你的意思是:targetInterface=&flash;
其中:flash是:FlashTarget flash
?@groenhen当然可以。你需要targetInterface
的指针吗?我是否应该将target
设置为全局变量以确保安全?只有在实例化的情况下de>target
用于初始化全局变量。如果您的代码与动态版本一起工作,则应与堆栈变量一起工作。最好完全消除全局变量。请注意,YSC将其方法描述为“幼稚”。如果静态对象在其析构函数中使用target
或targetInterface
,您可能会遇到问题,因为静态对象是在执行main
后被析构函数的,IIRC。@Peter naive在这里并不意味着不好。我将其与提供的信息一起使用,这是回答问题的最简单的解决方案。(只是澄清一下)