A variable array as a member of a class: why is it compiled?

I have a situation that I can not explain why it compiles:

#include <iostream> using namespace std; class X { public: X() {cout << "in X constructor: " << endl;}; }; class Y { public: Y() {cout << "in Y constructor" << endl;}; private: X x[]; }; int main() { Y y; return 0; } 

I define an array of variables of size X as a member of class Y Defining X is such a way outside the class will undoubtedly lead to a compilation error, but not inside the class. Moreover, constructor X never called.

So what is going on here?

+6
source share
1 answer

C99, 6.7.2.1/16 (n1256)

As a special case, the last structure element with more than one named element may have an incomplete array type; this is called a flexible array element. In most situations, the flexible array element is ignored. In particular, the size of the structure looks as if the flexible element of the array were excluded, except that it may have a longer addition than an omission would mean.

This is not a variable length array. This is not a bit of a data element, it is more like an interface to tell the compiler that you can access some memory using the name of a flexible array element.

/ 17

EXAMPLE After the announcement:

 struct s { int n; double d[]; }; 

struct s has a flexible array element d . Typical use:

 int m = /* some value */; struct s *p = malloc(sizeof (struct s) + sizeof (double [m])); 

and provided that the malloc call is complete, the object pointed to by p behaves for most purposes, as if p had been declared as:

 struct { int n; double d[m]; } *p; 

This is not allowed in C ++ 11, but is accepted by g ++ and clang ++ as an extension. Since the number of elements is not known to the struct constructor (for C ++), the constructor cannot initialize these elements (automatically).

+11
source

All Articles