You need to use unique_ptr version for dynamically allocated arrays:
std::unique_ptr<std::list<int>[]> map1(new std::list<int>[10]);
^^ ~~~~~ !
See here: http://en.cppreference.com/w/cpp/memory/unique_ptr :
template <
class T,
class Deleter
> class unique_ptr<T[], Deleter>;
You can also use std::make_unique (as suggested in comments) with which you would get compile error instead of UB, as its interface protects against it:
std::unique_ptr<std::list<int>[]> up1 = std::make_unique<std::list<int>[]>(10);
auto up2 = std::make_unique<std::list<int>[]>(10);
[edit]
However this code successfully ran.
unique_ptr map2(new int[10]);
Its still Undefined Behaviour in above code, it may work or may cause seg fault. unique_ptr as above accepts any pointer but will always call delete
during destructon. Calling delete
on pointer which points to dynamically allocated array is UB. Thats why you need to call delete[]
and this is what does unique_ptr
for dynamically allocated arrays.