简体   繁体   English

删除动态分配的数组与单指针

[英]Deleting dynamically allocated array vs single pointer

So I'm trying to implement a unique pointer and I want to be able to choose between allocating a single object and allocating an array.所以我正在尝试实现一个唯一指针,并且我希望能够在分配单个 object 和分配数组之间进行选择。

Let's say if I allocated everything with new[] even the single object( new[1] ) instead of choosing between new T(Args...) and new[n] T(Args...) depending on the constructor params, would deleting like this:假设我使用new[]分配所有内容,甚至是单个对象( new[1] ),而不是根据构造函数参数在new T(Args...)new[n] T(Args...)之间进行选择,会像这样删除:

delete[] this->ptr;

have any drawbacks vs有什么缺点vs

if (1 < size) {
    delete[] this->ptr; // this was allocated with new[]
    return;
}
delete this->ptr; // this was allocated with new

Thanks for the answer(s) in advance.提前感谢您的回答。

Usually, a unique pointer works by taking ownership of a bare pointer provided by the client: unique_ptr::unique_ptr(T*) .通常,唯一指针通过获取客户端提供的裸指针的所有权来工作: unique_ptr::unique_ptr(T*) In such case, it would be somewhat limiting for the client that they are not allowed to pass pointers to array of size 1 (in one choice of implementation), or that they are not supposed to pass pointers to non-arrays (the other choice).在这种情况下,客户端不允许将指针传递给大小为 1 的数组(在一种实现选择中),或者它们不应该将指针传递给非数组(另一种选择)。

Furthermore, both choices introduce extra, although tiny overhead.此外,这两种选择都会带来额外的开销,尽管开销很小。 One choice has a branch, and the other stores the size of the array, which isn't necessary for non-array allocation.一种选择有一个分支,另一种选择存储数组的大小,这对于非数组分配不是必需的。

The way the standard unique pointer is specified, the client gets to choose which limitation they want to have.指定标准唯一指针的方式,客户端可以选择他们想要的限制。 To use the non-array delete, you instantiate unique_ptr<T> , and to use array delete, you instantiate unique_ptr<T[]> specialisation.要使用非数组删除,请实例化unique_ptr<T> ,要使用数组删除,请实例化unique_ptr<T[]>化。 And because the choice is at compile time, there is no need for a runtime branch.而且因为选择是在编译时进行的,所以不需要运行时分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM