为什么c++子类中的字符串会导致内存泄漏
Why does a string in a C++ subclass cause memory leaks?
我花了2个多小时找到这个内存泄漏:
class Parent{
...
}
class Child:public Parent{
std::string str;
...
}
int main(){
Parent *ptr=new Child();
delete ptr;
}
我通过将字符串移动到父类中来修复它。为什么会发生内存泄漏?子节点的成员不也应该被删除吗?
这可能发生,因为Parent
可能没有虚析构函数。由于您正在为动态分配的派生类Child
创建Parent*
(基类),因此删除没有虚拟析构函数的Parent*
将导致未定义行为,但通常会导致派生类不被销毁。
From Scott Myers - Effective c++第三版:
…如果用非虚析构函数删除基类指针,则结果是未定义的。通常在运行时发生的情况是,对象的派生部分永远不会被销毁。这是泄漏资源、破坏数据结构和在调试器上花费大量时间的极好方法。因此,任何带有虚函数的类几乎都应该有虚析构函数。
class Parent{
};
class Child:public Parent{
public:
Child() : str("Child") {}
~Child() { std::cout << str << std::endl;};
std::string str;
};
int main(){
Parent *ptr=new Child();
delete ptr; // undefined behaviour: deleting a Base* to a Derived object where the Base has no virtual destructor
}
可以通过使Parent
的析构函数virtual
:
来解决这个问题class Parent{
public:
virtual ~Parent() {} // Will call derived classes destructors now as well
};
class Child:public Parent{
public:
Child() : str("Child") {}
~Child() { std::cout << str << std::endl;};
std::string str;
};
int main(){
Parent *ptr=new Child();
delete ptr;
// Child::~Child() has now been called.
}
参见何时使用虚析构函数?这可能比我解释得更好
编辑:感谢@aschepler(在问题的评论中),下面的评论以及链接问题的答案,我已经更新了答案,以更好地反映这是未定义的行为。在匆忙中我没有提及它,只提到了典型的行为
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏