当内存分配发生在预定义存储中时,如何强制清理程序检测内存泄漏? 下面是一个例子
#include <iostream>
#include <type_traits>
class A
{
};
typename std::aligned_storage<256, alignof(256)>::type store;
A * foo()
{
return new (&store) A();
}
A * bar()
{
return new A();
}
int main() {
A * a = foo();
a = foo();
A * a2 = bar();
a2 = bar();
}
当调用bar时检测到内存泄漏。 但是当 foo 被调用时不会 演示
您的
A
是“微不足道的可破坏”,这意味着(引用自 std::trivially_destructible
的 cppref 文档):
可以重用普通可破坏对象占用的存储空间,而无需调用析构函数。
多次调用
foo
不会导致内存泄漏,因为foo
本身不分配任何内存。
这段代码完全没问题,清理人员没有理由抱怨:
#include <iostream>
#include <type_traits>
class A
{
};
typename std::aligned_storage<256, alignof(256)>::type store;
A * foo()
{
return new (&store) A();
}
int main() {
A * a = foo();
a = foo();
std::cout << std::is_trivially_destructible<A>::value;
}
1