C++ 中的容器与智能指针

Ari*_*ris 4 c++ containers smart-pointers

std::vector在 std::containers (或std::array)和指向数组的智能指针之间进行选择时如何决定

我知道容器是内存管理的对象。它们是异常安全的,不会有任何内存泄漏,它们还提供了内存管理的功能(push.back等),而智能指针也是不会泄漏内存的指针,因为它们在不再需要时会删除它们(就像超出范围时的 unique_ptr 一样)。在容器中,每次创建它们时可能都会产生开销。

我的问题是我如何决定使用哪种方法以及为什么。

std::vector <unsigned char>myArray(3 * outputImageHight * outputImageWidth);

std::unique_ptr<unsigned char[]>myArray(new unsigned char[3 * outputImageHight * outputImageWidth]);
Run Code Online (Sandbox Code Playgroud)

Kar*_*oll 6

我会使用向量。您的指针版本基本上没有对矢量进行任何改进,并且您失去了许多有用的功能。您很可能需要测量大小并在某个时刻迭代您的数组,使用您免费获得的向量,而您需要自己为您的指针版本实现它;此时您可能刚刚开始使用向量。

实例化向量可能会产生性能成本,但我怀疑这会成为大多数应用程序的瓶颈。如果您创建了如此多的向量,以至于实例化它们会花费您的时间,那么您可能可以更聪明地管理它们(池化内存、自定义向量分配器等)。如有疑问,请进行测量。

您可能需要使用该unique_ptr<>版本的一个示例可能是,如果您正在使用用 C 编写的库,但您失去了数组的所有权。例如:

std::unique_ptr<unsigned char[]>myArray(
    new unsigned char[3 * outputImageHight * outputImageWidth]);

my_c_lib_data_t cLibData;
int result = my_c_lib_set_image(cLibData, myArray);

if (MYLIB_SUCCESS == result)
    // mylib successfully took ownership of the char array, so release the pointer.
    myArray.release();
Run Code Online (Sandbox Code Playgroud)

不过,如果可以选择,最好尽可能使用 C++ 风格的容器。