How to declare an array without a specific size?

How can I declare an array without a specific size as a member of a class? I want to set the size of this array immediately in the constructor of the class. Is it possible to do such a thing without using a heap or without resizing the array?

+4
source share
5 answers

Variable-length masks are not allowed by the C ++ standard. Possible options:

  • Use std::vector or
  • Use a pointer to dynamic memory

Note that variable length arrays are supported by most compilers as an extension. Therefore, if portability does not bother you, and your compiler supports it, you can use it. Of course, it has its own share of problems, but its option, taking into account the limitations that you indicated.

+5
source

C ++ requires that the size of the automatic storage be known at compile time, otherwise the array must be dynamically allocated. So you need dynamic allocation at some level, but you don't have to worry about doing it directly: just use std::vector :

 #include <vector> class Foo { public: Foo() : v_(5) {} private: std::vector<int> v_; }; 

Here v_ is a vector holding ints and has a size of 5 . The vector will take care of the dynamic allocation for you.

In C ++ 14, you will have the opportunity to use std::dynarray , which is very similar to std::vector , except that its size is fixed during construction. This closely matches the simple dynamically distributed array functionality.

+3
source

You can use the vector by including the header file #include<vector> It can grow and shrink in size as needed, and vectors are built into methods / functions that can make your work easier.

0
source

An array of a class member must be declared with the exact compile-time size. There is no way around this.

The only way to declare an array as a direct member of a class and still be able to determine its size at runtime is with the popular "struct hack" method inherited from C.

In addition, you must declare your array as an indirect member of the class: either declare a member of the pointer type, or allocate memory later, or use some library implementation of the runtime array (for example, std::vector )

0
source

The only way to allocate a dynamic array in C ++ without using a heap is to do it on the stack.

 void func(int size) { int my_array[size]; } 

Then you can pass this pointer to your class:

 class stuff { public: stuff(int *ary) : f_array(ary) {} private: int *f_array; }; stuff my_stuff(my_array); 

Now, to be honest, I would use std :: vector <> (), as presented in other answers that will allocate memory from the heap, but has all the necessary security measures that will help you write much more secure code.

-2
source

Source: https://habr.com/ru/post/1487691/


All Articles