Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of objects of myarray on the stack and how can you create an array of objects on the heap?
Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of objects of myarray on the stack and how can you create an array of objects on the heap?
Since C++11
std::array<T,size>
is available for arrays allocated on the stack. It wrapsT[size]
providing the interface ofstd::vector
, but the most of the methods areconstexpr
. The downside here is that you never know when you overflow the stack.For arrays allocated with heap memory use
std::vector<T>
. Unless you specify a custom allocator the standard implementation will use heap memory to allocate the array members.Note that in both cases a default constructor is required to initialize the array, so you must define
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.If you create an array of objects of class myarray ( either on stack or on heap) you would have to define a default constructor.
There is no way to pass arguments to the constructor when creating an array of objects.
You can create an array of objects on the stack† via:
And on the heap† (or "freestore"):
But it's best not manage memory yourself. Instead, use a std::vector:
A vector is a dynamic array, which (by default) allocates elements from the heap.††
Because your class has no default constructor, to create it on the stack you need to let the compiler know what to pass into the constructor:
Or with a vector:
Of course, you could always give it a default constructor:
† For the pedants: C++ doesn't really have a "stack" or "heap"/"freestore". What we have is "automatic storage" and "dynamic storage" duration. In practice, this aligns itself with stack allocation and heap allocation.
†† If you want "dynamic" allocation from the stack, you'd need to define a max size (stack storage is known ahead of time), and then give vector a new allocator so it uses the stack instead.
I know how to create object with out of the default constructor, but only on stack:
Suppose you want to create 10 objects for MyArray class with
a = 1..10
:No need to call the destructor, because they are created in the stack.