Reputation: 123
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.
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:
delete[] this->ptr;
have any drawbacks 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.
Upvotes: 1
Views: 53
Reputation: 238331
Usually, a unique pointer works by taking ownership of a bare pointer provided by the client: 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).
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. And because the choice is at compile time, there is no need for a runtime branch.
Upvotes: 1