Since I've also spent some time on this: my take on this is that the C++ FE
should just follow C FE's suit and reject such initializations where
possible; it seems they've never worked reliably anyway, and bring more
harm than good.  I don't see that rejecting such code would cause too much
trouble, if any, although the timing could be better.

Schedule concerns aside, and although I agree that rejecting such
code is far preferable to generating buggy programs, I'm not sure
that rejecting auto initialization of flexible array members will
ultimately lead to the best results.  Users who want to initialize
local objects with flexible array members will find some other
(likely convoluted) way that GCC may not be able to find bugs in.
A possible solution for those who can't or don't want to use
std::array might be something like this:

  void f ()
  {
    struct S { size_t n; int a[]; };

    S *ps = (S*)alloca (sizeof (S) + 5);

    ps->n = 5;
    memcpy (ps->a, (const int[]){ 1, 2, 3, 4, 5 }, sizeof *ps->a * 5);

    ...
  }

but that's clearly error-prone and hard to diagnose.  GCC has
no mechanism to detect bugs in this code without optimization,
and because it folds the memcpy into a bunch of assignments,
-Wstringop-overflow doesn't detect buffer overflows in the
call to the function.

I think it would be better to get the initialization to work so
that users don't have to jump through hoops and can instead write
cleaner code that more readily lends itself to checking for bugs.
It might be even worth proposing local initialization as
an enhancement for C2X.

Martin

Reply via email to