One additional reason to allow and use std::unique_ptr<T[]>
, that hasn't been mentioned in the responses so far: it allows you to forward-declare the array element type.
This is useful when you want to minimize the chained #include
statements in headers (to optimize build performance.)
For instance -
myclass.h:
class ALargeAndComplicatedClassWithLotsOfDependencies;
class MyClass {
...
private:
std::unique_ptr<ALargeAndComplicatedClassWithLotsOfDependencies[]> m_InternalArray;
};
myclass.cpp:
#include "myclass.h"
#include "ALargeAndComplicatedClassWithLotsOfDependencies.h"
// MyClass implementation goes here
With the above code structure, anyone can #include "myclass.h"
and use MyClass
, without having to include the internal implementation dependencies required by MyClass::m_InternalArray
.
If m_InternalArray
was instead declared as a std::array<ALargeAndComplicatedClassWithLotsOfDependencies>
, or a std::vector<...>
, respectively - the result would be attempted usage of an incomplete type, which is a compile-time error.