How do smart pointers choose between delete and delete[]?

Unfortunately, they don’t know what delete to use therefore they use delete. That’s why for each smart pointer we have a smart array counterpart.

std::shared_ptr uses delete
std::shared_array uses delete[]

So, your line

std :: unique_ptr <int> x (new int [2]);

actually causes undefined behavior.

Incidentally, if you write

std :: unique_ptr<int[]> p(new int[2]);
                     ^^

then delete[] will be used since you’ve explicitly requested that. However, the following line will still be UB.

std :: unique_ptr<int[]> p(new int);

The reason that they can’t choose between delete and delete[] is that new int and new int[2] are exactly of the same type – int*.

Here’s a related question of using correct deleters in case of smart_ptr<void> and smart_ptr<Base> when Base has no virtual destructor.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)