我在我的代码中发现了一个内存泄漏,这是由于仅调用对象的基类析构函数引起的。这个问题理解:我已经virtual
在接口类的析构函数中添加了MyÌnterface
。令我困惑的是,编译器显然为我的帮助类创建了一个标准的析构函数,MyHelper
最终被调用。我用两个不同的编译器试过这个。
这让我非常惊讶,因为我观察到如果成员或基类引入限制,大多数默认实现都不会创建。为什么不继承析构函数的保护?
#include <iostream>
class MyInterface
{
public:
virtual void doSomethingUseful()=0;
// a lot more functions declared omitted
virtual void doSomethingElse()=0;
virtual void doSomethingIndividual()=0;
protected:
/// protected destructor to forbid calling it on interfaces
~MyInterface() {} // HERE the virtual is clearly missing
};
/// a common base that defaults most functions implementations
class MyHelper: public MyInterface
{
public:
void doSomethingUseful() {}
// a lot more default implementations omitted
void doSomethingElse() {}
};
class SomeImplementation: public MyHelper
{
public:
SomeImplementation()
{
std::cout << "SomeImplementation ctr" << std::endl;
}
~SomeImplementation()
{
std::cout << "SomeImplementation dtr" << std::endl;
}
void doSomethingIndividual()
{
std::cout << "SomeImplementation did it." << std::endl;
}
};
/// user of MyInterface cannot delete object mi passed as parameter
int deleteSafeUsage(MyInterface& mi)
{
mi.doSomethingIndividual();
// would cause a compiler error: delete &mi;
}
/// usage restricted to MyHelper level, only exception is object creation
int testIt()
{
MyHelper* h = new SomeImplementation;
deleteSafeUsage(*h);
delete h; // <- HERE the memory leak happens!
}
这里是上面示例代码的输出,它“显示”了缺失的SomeImplementation ctr
:
SomeImplementation ctr
SomeImplementation did it.