Reputation: 1369
I'm trying to implement a unique_ptr class in C++, but how to know if the pointer we passed to it was allocated with new
or new[]
without using default_delete
(my school standard doesn't allow c++11).
I mean when you pass your pointer to the constructor like this for example:
unique_ptr<int> ptr(new int[10]);
how do you know inside of the class if you need to call delete[]
or delete
?
Upvotes: 4
Views: 145
Reputation: 96579
You can't tell. And neither can std::unique_ptr
.
Think about it. If it could be determined automatically, you wouldn't need two kinds of delete
.
std::unique_ptr<int> ptr(new int[10]);
is wrong, since it will call delete
, rather than delete[]
.
Use std::unique_ptr<int[]> ptr(new int[10]);
instead, which will call delete[]
, rather than delete
.
Upvotes: 6