Set array field's length based on const integer field

91 Views Asked by At

Suppose I have a class...

class Foo
{
public:
  Foo(int size);

private:
  const int size;
  int data[];
};

Supposing that the size field is set immediately at instantiation, how can I set the length of data based on that size input?

I would ordinarily use a std::vector here, but I am writing a library for Arduino, so that won't fly, and I'm trying to avoid external dependencies if I can.

1

There are 1 best solutions below

0
On BEST ANSWER

You are out of luck here, as C++ must know the size of the array at compile time (in other words, the size must be a constant expression). Your options are to either use dynamic allocation

int* data;  

then allocate with new int[size]; in the constructor initialization list, or, better, use std::unique_ptr<> (C++11 or later), which is a light wrapper around a raw pointer and deletes its allocated memory at scope exit, so you won't have to manually delete[]

class Foo
{
private:
    std::unique_ptr<int[]> data; // no need to manually delete
public:
    Foo(int size): data{new int[size]} {}
};

A third option is to make Foo a non-type template class (assuming you know the size at compile time, which is what it seems to be happening, at least judging from your question)

template<std::size_t size>
class Foo
{
    int data[size];
public:
    Foo() 
    {
        // constructor here
    }
};