How can I retrieve the size of a smart pointer array? (e..g std::unique_ptr<int[]>)

arrays, c++, pointers

Solution

With both `new[]`/`delete[]` and `malloc`/`free`, the size is indeed stored somewhere, but there is no standardized way to access that information.

Problem

Heap-allocated c arrays don't retain any size information, as pointed out here: How can i find the size of a dynamically allocated array in C? However, smart pointers in c++11 have the ability to store memory and manage c-arrays with the array versions using the subscript (`[]`) operator overload: ``` std::unique_ptr<int[]> arr(new int[val]); ``` When this smart pointer goes out of scope, it presumably deallocates the owned block of memory, so it must store the size of the memory block somewhere. How can I retrieve the size of the c array allocated on `arr` in the above example, assuming that `val` is a runtime variable?

Original source