我已经实现了一个功能,其中身份被赋予给我并且不受我的控制。它返回std::shared_ptr<const void>
。在函数中,我分配任意数量的内存,并通过shared_ptr返回对它的访问。
我的内存分配完成了new unsigned char[123]
。问题在于 valgrind 检测到 new 变体和删除变体的使用之间不匹配。当我使用new[](unsigned)
为了分配内存,shared_ptr 析构函数使用delete(void*)
解除分配它,每当您使用“不正确”的解除分配器进行分配时,valgrind 都会发出警告。
从更实际的角度来说,我编写了这个测试用例来展示我的意思:
TEST(Example, Test1)
{
unsigned char* mem = new unsigned char[123];
std::shared_ptr<const void> ptr(mem);
}
valgrind 报告称
==45794== Mismatched free() / delete / delete []
==45794== at 0x4C2A64B: operator delete(void*) (vg_replace_malloc.c:576)
==45794== by 0x40B7B5: _M_release (shared_ptr_base.h:150)
==45794== by 0x40B7B5: ~__shared_count (shared_ptr_base.h:659)
==45794== by 0x40B7B5: ~__shared_ptr (shared_ptr_base.h:925)
==45794== by 0x40B7B5: ~shared_ptr (shared_ptr.h:93)
==45794== by 0x40B7B5: Example_Test1_Test::TestBody() (test.cc:108)
==45794== Address 0x5cb6290 is 0 bytes inside a block of size 123 alloc'd
==45794== at 0x4C29CAF: operator new[](unsigned long) (vg_replace_malloc.c:423)
==45794== by 0x40B72E: Example_Test1_Test::TestBody() (test.cc:107)
如果可能的话,我想避免使用 valgrind 过滤器。
分配任意数量的数据并作为返回的正确方法是什么std::shared_ptr<const void>
?
如果你给shared_ptr<T>
a T
指针,它假设您创建了一个对象并暗示了删除器delete p;
。如果您的分配实际上是使用 array-new 执行的,则需要传递一个适当的删除器来执行delete[] p;
。您可以重复使用std::default_delete
如果你喜欢:
return static_pointer_cast<const void>(
std::shared_ptr<unsigned char>(
new unsigned char[N],
std::default_delete<unsigned char[]>()));
(您甚至不需要外部转换,因为转换是隐含的。)
在 C++17 中,shared_ptr
支持数组,所以你可以说
shared_ptr<unsigned char[]>(new unsigned char[N])
在那里并获得正确的删除器(然后转换为 void)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)