2

I asked this question before. But now I am wondering why the following is also valid or invalid:

class C {
    int n;
    int a[n];
};
template <typename T, int n> class A {
    int a[n];
};

I tested them in g++ and they seemed to work. Are they the same as VLA in the case when inside a function, or they are different? Besides, I can now make the array parts on heap besides on stack too.

Community
  • 1
  • 1
Qiang Li
  • 10,593
  • 21
  • 77
  • 148

2 Answers2

2

A VLA has its size determined at runtime. VLAs are not in C++, even though g++ implements them.

Since templates are a compile-time mechanism, the array A::a will have its size determined at compile time. The array C::a is invalid, though, because c::n is not a compile time constant.

Try compiling with warnings enabled and with -std=c++98 or -std=c++0x.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
1

1st isn't valid unless n is constant. If it was allowed, sizeof wouldn't work correctly.

2nd. isn't truly a VLA, as n has to be constant:

void foo(int n) {
  A<int, n> x; // error
}

If you want semi-portable VLAs then use alloca function. Or use std::vector if you don't care about it being on the heap.

void foo(int n) {
  int a[n];                         // VLA extension, somewhat portable
  int* b = alloca(n * sizeof(int)); // alloca, somewhat portable (should work on MSVC)
  std::vector<int> c(n);            // portable
}
Pubby
  • 51,882
  • 13
  • 139
  • 180