Creating array of objects on the stack and heap

Viewed 79899

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?

6 Answers

To use stack memory allocated with a max size, and view it through a standard stl container with a run time chosen size, you can use std::span.

#include <span>
using namespace std;

struct Toto{ int i; char name[20];};
Toto mem[100];
int n=3;
std::span<Toto> s(&mem[0], n);

my use case involves a function that gets called a million times and makes use of a few arrays (currently std::vectors). I wonder if it would be faster to replace std::vector this way. Havent't tried yet... Another possibility would be to allocate std::vector's once instead of a million times.

Related