Home > database >  Declare static array in class with size passed to constructor?
Declare static array in class with size passed to constructor?

Time:04-01

Is there any way, to declare static array in class with size that was passed to constructor? It is alright if the size has to be const and it makes it impossible to set it in runtime.

I tried doing something like this:

class class_name
{
    public:
        float* map;
        class_name(int n, const int d)
        {
            float arr[d];
            map = arr;
        }
};

but I feel like it could be very bad idea. Is it bad? If it is, then why is it?

CodePudding user response:

Yes, this code

    class_name(int n, const int d)
    {
        float arr[d];
        map = arr;
    }

is a bad idea, for 2 reasons

  1. float arr[d]; creates a local variable in stack, so it ceases to exist at the end of the block. So map becomes a dangling pointer. If you needed dynamic size allocation, you should just use std::vector<float> map and avoid a lot of hassle.
  2. float arr[d]; is a variable length array, and C does not support those. Making d be const does not help, it has to be an actual constant, not const variable.

Solution: Since you say the array length can be determined at compile time, this is perfect fit for a template:

template <std::size_t N>
class class_name
{
    public:
        std::array<float, N> map { {} }; // { {} } causes value initialization of everything to 0
        // actually above could be `float map[N];` but it has the C array gotchas
        
        class_name(int n)
        {
            // not sure what n is for...
        }
};

And to declare a variable of this class:

class_name<5> obj; // obj.map size is 5

CodePudding user response:

By 'static array', do you mean something of unchanged size? std::unique_ptr<float[]>, and std::make_unique(std::size_t), might be an option.

  • Related