c++ - 创建包含已分配数组的 unique_ptr 的正确方法

标签 c++ linux gcc c++11 unique-ptr

创建一个unique_ptr 的正确方法是什么,它包含一个在自由存储上分配的数组? Visual Studio 2013 默认支持这一点,但是当我在 Ubuntu 上使用 gcc 4.8.1 版时,我会遇到内存泄漏和未定义的行为。

这个问题可以用这段代码重现:

#include <memory>
#include <string.h>

using namespace std;

int main()
{
    unique_ptr<unsigned char> testData(new unsigned char[16000]());

    memset(testData.get(),0x12,0);

    return 0;
}

Valgrind 会给出这个输出:

==3894== 1 errors in context 1 of 1:
==3894== Mismatched free() / delete / delete []
==3894==    at 0x4C2BADC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894==    by 0x400AEF: std::default_delete<unsigned char>::operator()(unsigned char*) const (unique_ptr.h:67)
==3894==    by 0x4009D0: std::unique_ptr<unsigned char, std::default_delete<unsigned char> >::~unique_ptr() (unique_ptr.h:184)
==3894==    by 0x4007A9: main (test.cpp:19)
==3894==  Address 0x5a1a040 is 0 bytes inside a block of size 16,000 alloc'd
==3894==    at 0x4C2AFE7: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894==    by 0x40075F: main (test.cpp:15)

最佳答案

使用 T[] 特化:

std::unique_ptr<unsigned char[]> testData(new unsigned char[16000]());

请注意,在理想情况下,您不必显式使用 new 来实例化 unique_ptr,从而避免潜在的异常安全陷阱。为此,C++14 为您提供了 std::make_unique 函数模板。见 this excellent GOTW更多细节。语法是:

auto testData = std::make_unique<unsigned char[]>(16000);

关于c++ - 创建包含已分配数组的 unique_ptr 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377360/

相关文章:

c - 在 GCC 进行的每次优化后获取汇编代码?

C++ 将多个 header 连接到一个 header 并使用这些 header 函数

c++ - 如果直接使用,constexpr 函数参数被认为是 constexpr,但如果用于调用另一个 constexpr 函数则不是

linux - 使用 Icinga 监控系统检查 Linux 主机上 ZFS 池的状态

c++ - 我如何在 linux 中使用 ctrl-c 使 wxTextCtrl 句柄

c - 如何在静态库中隐藏目标文件名?

c++ - 过滤范围、lambda 和 is_sorted

c++ - 为什么我的子窗口对鼠标事件没有反应?

linux - 使用 Electron 自定义形状的独立 Windows 应用程序

c - GCC 中该表达式中的值是如何计算的