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
float arr[d];
creates a local variable in stack, so it ceases to exist at the end of the block. Somap
becomes a dangling pointer. If you needed dynamic size allocation, you should just usestd::vector<float> map
and avoid a lot of hassle.float arr[d];
is a variable length array, and C does not support those. Makingd
beconst
does not help, it has to be an actual constant, notconst
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.