Mar*_*n G 4 c++ memory-management shared-ptr c++11
我已经实现了一个功能,其中身份被赋予我并且不受我的控制.它回来了std::shared_ptr<const void>.在函数中,我分配了任意数量的内存,并通过shared_ptr返回对它的访问.
我的内存分配完成了new unsigned char[123].问题是valgrind检测到new和delete变体的使用不匹配.当我new[](unsigned)用来分配内存时,shared_ptr析构函数delete(void*)用来释放它,而valgrind会在你使用"不正确"的deallocator进行分配时发出警告.
在更实际的术语中,我写了这个测试用例来表明我的意思:
TEST(Example, Test1)
{
unsigned char* mem = new unsigned char[123];
std::shared_ptr<const void> ptr(mem);
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想避免使用valgrind过滤器.
分配任意数量的数据并返回的正确方法是std::shared_ptr<const void>什么?
Ker*_* SB 13
如果你给shared_ptr<T>一个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[]>()));
Run Code Online (Sandbox Code Playgroud)
(你甚至不需要外部演员,因为隐含了转换.)
在C++ 17中,shared_ptr支持数组,所以你可以说
shared_ptr<unsigned char[]>(new unsigned char[N])
Run Code Online (Sandbox Code Playgroud)
在那里得到正确的删除器(然后转换为void).