"const variables" defined by the constructor to express the boundaries of a C ++ array?

The following code compiles and seems to work fine:

class Test { private: const unsigned MAX; public: Test (const unsigned int n) : MAX(n) { } void foo () { int array[MAX]; ... } }; 

but is everything alright? I mean:

 Test a (3); Test b (8); 

Does array really have 3 and 8 cells respectively?

If so, is that because array is automatic var and gets an instance with the appropriate size?

thanks

+4
source share
3 answers

What you wrote is valid in , but not valid .

Of course, I'm talking about your use of VLA , not the full snippet.


When compiling using g++ -pedantic -ansi -Wall we get the warning below:

 foo.cpp: In member function 'void Test::foo()': foo.cpp:18:23: warning: ISO C++ forbids variable length array 'array' [-Wvla] 

As mentioned above, the pattern you use is often referred to as using a variable-length array, which is standard in C99 and is "allowed" in C ++ through the g ++ extension.

I would recommend you use an STL container instead of hacks, as this is for one single reason; what you do is not legal and therefore portable cross-compilers are not guaranteed.

+4
source

Variable-length masks are not standard C ++. Instead, you can make a Test pattern:

 template <int MAX> class Test { public: Test () {} void foo () { int array[MAX]; } }; Test<4> t4; Test<8> t8; 
+4
source

You are right that this is not legal C ++. If it works with your compiler, probably because you are using the GCC extension.

+1
source

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


All Articles