As far as I know, calling std::unique_ptr<T,Deleter>::release
only transfers ownerships, won't free the dynamic memory.
From C++ Primer 5th:
p2.release(); // WRONG: p2 won't free the memory and we've lost the pointer
auto p = p2.release(); // ok, but we must remember to delete(p)
But after a few pages it writes:
The library provides a version of
unique_ptr
that can manage arrays allocated by new. To use aunique_ptr
to manage a dynamic array, we must include a pair of empty brackets after the object type:
// up points to an array of ten uninitialized ints
unique_ptr<int[]> up(new int[10]);
up.release(); // automatically uses delete[] to destroy its pointer
The brackets in the type specifier (
<int[]>
) say that up points not to an int but to an array of ints. Because up points to an array, when up destroys the pointer it manages, it will automatically usedelete[]
.
So is it true that std::unique_ptr<T,Deleter>::releas
treats dynamically allocated array differently, which is freeing the allocated memory automatically after calling release()
? If it's true, then it also indicates that one can't transfer ownership of an dynamic array. I couldn't find any authoritative references on the Web so far.