本文介绍了创建持有已分配数组的unique_ptr的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个unique_ptr来保存在免费商店中分配的数组的正确方法是什么? Visual Studio 2013默认情况下支持此功能,但是当我在Ubuntu上使用gcc版本4.8.1时,会出现内存泄漏和未定义的行为.

What is the proper way to create an unique_ptr that holds an array that is allocated on the free store? Visual studio 2013 supports this by default, but when I use gcc version 4.8.1 on Ubuntu I get memory leaks and undefined behaviour.

可以使用以下代码重现该问题:

The problem can be reproduced with this code:

#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将给出以下输出:

Valgrind will give this output:

==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函数模板.有关更多详细信息,请参见此出色的GOTW .语法为:

Note that, in an ideal world, you would not have to explicitly use new to instantiate a unique_ptr, avoiding a potential exception safety pitfall. To this end, C++14 provides you with the std::make_unique function template. See this excellent GOTW for more details. The syntax is:

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

这篇关于创建持有已分配数组的unique_ptr的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:30