您可以使用内存泄漏检测器或垃圾收集器。我个人将 Boehm GC 用作垃圾收集器,但也可以将其用作泄漏检测器。我的朋友使用 valgrind 进行内存泄漏检测。
也可以从自定义对象派生所有类,该对象在静态 std::set 结构中跟踪所有分配的对象;构造函数将“this”插入此结构,析构函数将其删除。然后,您可以在程序末尾使用静态 Object::detectMemoryLeaks() 打印出所有泄漏对象及其 typeid(ptr).name()。
编辑:
我在过去几个小时内将我的版本实现到了我的库中。找不到排除静态变量或自动确定多态对象大小的方法。另外,请原谅类似 java 的外星代码和垃圾收集的存在:标头和实现。查找构造函数、析构函数、aliveObjects 静态属性和 listAliveObjects 静态方法。你可以很容易地了解这个概念的要点。
示例输出:
Frigo::Lang::Array<char> : 6 objects
Frigo::Lang::String : 6 objects
Frigo::Lang::Boolean : 2 objects
Frigo::Lang::Integer : 2 objects
Frigo::Math::Infinity : 1 objects
Frigo::Lang::Class : 1 objects
----
Frigo::Lang::Array<char> : 7 objects @ 0x1d33e18, 0x1d33e78, 0x1d33ed8, 0x1d33f38, 0x1d33f68, 0x1d33f98, 0x1d33fc8
Frigo::Lang::String : 7 objects @ 0x1d33e10, 0x1d33e70, 0x1d33ed0, 0x1d33f30, 0x1d33f60, 0x1d33f90, 0x1d33fc0
Frigo::Lang::Boolean : 2 objects @ 0x1d30fa8, 0x1d30fd8
Frigo::Lang::Integer : 2 objects @ 0x1d30e88, 0x1d30eb8
Frigo::Lang::Class : 1 objects @ 0x1d30f60
Frigo::Math::Infinity : 1 objects @ 0x41a110
----
Frigo::Lang::Array<char> : 6 objects
Frigo::Lang::Array<char>@3b3e78
Frigo::Lang::Array<char>@3b3ed8
Frigo::Lang::Array<char>@3b3f38
Frigo::Lang::Array<char>@3b3f68
Frigo::Lang::Array<char>@3b3f98
Frigo::Lang::Array<char>@3b3fc8
Frigo::Lang::String : 6 objects
Frigo::Lang::Boolean
Frigo::Lang::Class
Frigo::Lang::Integer
Hello World!
true
false
Frigo::Lang::Boolean : 2 objects
true
false
Frigo::Lang::Integer : 2 objects
987
123
Frigo::Math::Infinity : 1 objects
Frigo::Math::Infinity@41a110
Frigo::Lang::Class : 1 objects
Frigo::Lang::Class@3b0f60
----
Frigo::Lang::Array<char> : 7 objects
@ 0x1cd3e18 : Frigo::Lang::Array<char>@1cd3e18
@ 0x1cd3e78 : Frigo::Lang::Array<char>@1cd3e78
@ 0x1cd3ed8 : Frigo::Lang::Array<char>@1cd3ed8
@ 0x1cd3f38 : Frigo::Lang::Array<char>@1cd3f38
@ 0x1cd3f68 : Frigo::Lang::Array<char>@1cd3f68
@ 0x1cd3f98 : Frigo::Lang::Array<char>@1cd3f98
@ 0x1cd3fc8 : Frigo::Lang::Array<char>@1cd3fc8
Frigo::Lang::String : 7 objects
@ 0x1cd3e10 : Frigo::Lang::Boolean
@ 0x1cd3e70 : Frigo::Lang::Class
@ 0x1cd3ed0 : Frigo::Lang::Integer
@ 0x1cd3f30 : Frigo::Math::Infinity
@ 0x1cd3f60 : Hello World!
@ 0x1cd3f90 : true
@ 0x1cd3fc0 : false
Frigo::Lang::Boolean : 2 objects
@ 0x1cd0fa8 : true
@ 0x1cd0fd8 : false
Frigo::Lang::Integer : 2 objects
@ 0x1cd0e88 : 987
@ 0x1cd0eb8 : 123
Frigo::Lang::Class : 1 objects
@ 0x1cd0f60 : Frigo::Lang::Class@1cd0f60
Frigo::Math::Infinity : 1 objects
@ 0x41b110 : Frigo::Math::Infinity@41b110