当在头文件上而不是在CPP文件上实现时,析构函数会导致内存泄漏——仅在linux上实现
A destructor function is causing memory leak when implemented on header file rather than on CPP file - only on linux
我们管理一些多平台代码,我遇到了只在linux上发生的最奇怪的内存泄漏。
我有一个类既不继承也不被继承。由于它没有任何需要释放的动态分配,我没有为它定义析构函数(它确实有一些自毁成员,没有一个是指针)。
我们注意到这个类的生成(new)和销毁(delete)导致了内存泄漏。在头文件上定义和实现一个空的析构函数并没有解决泄漏问题。将实现移动到源文件-确实解决了它。这(泄漏)不会发生在windows上,但会发生在linux上。
我想这与编译器优化有关,但如果是这样的话,我真的想知道这个现象的基础,所以我会知道如何避免再次出现这种泄漏。
有人知道为什么会发生这种事吗?
这是代码的草图(当然不是真正的…)
//file config.h
class Config
{
public:
Config(std::shared_ptr<PR_Config> prConfig)
{mPRConfig = engineConfig; mConfigOccurences++;};
~Config(){}
shared_ptr<PR_Config>...
...
...
...
//some public functions
private:
shared_ptr<PR_Config>...
...
...
...
//some private members of shared_ptr type
};
//file: ConfigChecker.cpp
bool ConfigChecker::CheckConfig()
{
shared_ptr<Config> localConfig;
localConfig = GenerateConfig();
//Do some stuff with local config. did not change the reference count...
if (locakConfig)
return true;
return false;
}
//file: Utils.cpp
shared_ptr<Config> GenerateConfig()
{
shared_ptr<Config> pConfig = new Config(/*som parameters here...*/)
return pConfig;
}
重要提示:
- 将~Config的实现移动到Config.cpp文件时,泄漏停止
- 我们并不真正使用sharedptr,而是使用其他一些具有引用计数和自毁功能的智能指针。但我不相信它在做
我已经看到了这种由前向声明和std::auto_ptr
创建的不完整类型的确切行为。
我相信shared_ptr
和unique_ptr
的当前版本已经通过使用显式析构函数解决了这个问题,如果定义不可见,它们将无法编译。
我怀疑你的"其他智能指针"没有这样做,或者做得不对。这很难做到正确。C++标准的人发明了auto_ptr
,并在解决这个问题之前使用了多年。
相关文章:
- 在实现文件中使用头文件的通用 lambda
- 如何使用命令提示符、记事本和 MinGW 使用主文件、头文件和实现文件编译C++程序?
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 在实现文件中使用模板参数声明方法
- 模板实现文件中的匿名命名空间
- 创建单独的实现文件和头文件
- 当我从头文件和实现文件调用我的函数到我的主文件时,我没有得到任何输出
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- 包含适当的标头时,实现文件中的多个定义出错
- 如何在结构中实现文件读取和创建
- 在头文件和实现文件中创建模板模板函数
- C++头/实现文件中的默认和重载构造函数?
- 如何在C++实现文件中实例化类?
- 实现文件只能识别其他类的远期声明
- C++ 将字符串值传递到实现文件时出现问题
- 创建头文件和实现文件时出现问题
- C 从实现文件中访问私有静态成员
- Pimpl习惯用法、单独的接口/实现文件和多个虚拟继承.如何
- 没有实现文件(.cpp)的派生类
- 在标题或实现文件中定义常数的优点