Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable size array as class member: why does it compile?

Tags:

c++

g++

mingw

I have this situation which I cannot 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 am defining a variable size array of X as a member of class Y. Defining X it is such a way outside the class would surely result in a compile error, but not within the class. What’s more, the constructor of X is never called.

So what is happening here?

like image 842
Davor Josipovic Avatar asked Feb 24 '14 14:02

Davor Josipovic


1 Answers

C99, 6.7.2.1/16 (n1256)

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

It is not a variable-length array. It isn't anything like a data member, more like an interface to tell the compiler you can access some memory via the name of the flexible array member.

/17

EXAMPLE After the declaration:

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

the structure struct s has a flexible array member d. A typical way to use this is:

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

and assuming that the call to malloc succeeds, 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 accepted by g++ and clang++ as an extension. As the number of elements isn't known to the constructor of the struct (for C++), the constructor cannot initialize those elements (automatically).

like image 166
dyp Avatar answered Nov 09 '22 14:11

dyp