为什么本文底部的代码会导致以下内存泄漏:
The thread 0x4ce4 has exited with code 0 (0x0).
Detected memory leaks!
Dumping objects ->
{159} normal block at 0x000001E980B91E80, 16 bytes long.
Data: <`^ > 60 5E B8 80 E9 01 00 00 00 00 00 00 00 00 00 00
{158} normal block at 0x000001E980B85E40, 136 bytes long.
Data: < [ [ > 90 5B B8 80 E9 01 00 00 90 5B B8 80 E9 01 00 00
{156} normal block at 0x000001E980B85B90, 136 bytes long.
Data: <@^ @^ > 40 5E B8 80 E9 01 00 00 40 5E B8 80 E9 01 00 00
{155} normal block at 0x000001E980B92BF0, 16 bytes long.
Data: <P 3 > 50 9B 17 33 F7 7F 00 00 00 00 00 00 00 00 00 00
Object dump complete.
代码:
#include "CrtDebug.h"
int main()
{
_CrtDumpMemoryLeaks();
return 0;
}
我确实有其他类和文件,但如您所见,它们都没有包含或用于我的 main 中。
_CrtDumpMemoryLeaks()
是否也以某种方式检查 main 中甚至没有包含或使用的类?这些内存泄漏的原因可能是什么?
我的项目中确实有静态函数和工厂方法模式的实现。我为这个工厂方法使用了一个模板类,并且在工厂方法模式代码的头文件中有一些静态方法。我还为工厂方法模式的(具体)组件使用静态实例变量。 但是,我没有在
main.cpp
.中包含或使用它们
编辑: 我有点发现问题出在哪里。我的工厂方法模式的具体组件有这样的静态实例:
#pragma once
#include "BaseComponent.h"
class Component1 : public BaseComponent {
public:
Component1() {}
Component1(int id);
bool run() const override;
private:
static Component1 instance;
};
源文件如下所示:
#include "Component1.h"
Component1 Component1::instance("ONE");
Component1::Component1(int id) : BaseComponent{ id, [] { return std::make_unique<Component1>(); } } {}
bool Component1::run() const {
// Logic
}
像这样为每个静态实例添加更多具体组件,会增加
_CrtDumpMemoryLeaks
输出中的内存泄漏数量。我希望此信息足以确定可能的最终原因或问题的解决方案。提前致谢。