Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of
Since C++11 std::arrayT[size]
providing the interface of std::vector
, but the most of the methods are constexpr
. The downside here is that you never know when you overflow the stack.
std::array stack_array; // Size must be declared explicitly.VLAs
For arrays allocated with heap memory use std::vector
std::vector heap_array (3); // Size is optional.
Note that in both cases a default constructor is required to initialize the array, so you must define
myarray::myarray() { ... }
There are also options to use C's VLAs or C++'s new
, but you should refrain from using them as much as possible, because their usage makes the code prone to segmentation faults and memory leaks.