1

I'm trying to use compounds the {} notation of initializer lists for initializing static local constants in C++11. The question might be a follow-up of one about temporary arrays. There may be a side track(?) hinting at const (but only for C99?). Another question brings heap allocation into view, but with a difference, I think.

The idea is for a function to establish a data structure in its own scope, once. A static (const) variable definition takes values from the lists as written (by misguided intention: C-style compound literals). Later, the function should be able to refer to the structure. The SO links above explain, both directly and indirectly, why just literals won't work.

Will new help, though?

int undef()
{
  static const int vs[3] {1,2,3};
  static const int* vss[2] {
    vs,
    // (const int[3]){1,2,3}          // temporary will be lost
    new const int[3] {1,2,3}
  };
  return vss[0][1] + vss[1][1];
}

My guess: new will allocate an array somewhere, initialize the new array from the temporary {1,2,3} and then that somewhere continues to have an address. So, nothing is lost. Correct?

Is the above use of new safe and sound, meaning covered by the standard? C++11 in my case.

B98
  • 1,229
  • 12
  • 20

1 Answers1

2

This is defined behavior. The only pedantic issue is a technical memory leak. Nothing will ever formally delete it, but it'll only be allocated once, and it'll exist for the entire program's execution. Big deal. The only practical annoyance would be static memory sanitizers reporting a "possible" memory leak, from something like this.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • It's exempt from avoiding "naked **new**" then, not a garbage collector around? Good. – B98 Dec 27 '22 at 16:18
  • There is no garbage collection in C++. – Sam Varshavchik Dec 27 '22 at 16:24
  • ("Garbage collection is optional in C++" (TCPL 4ed, § 34.5). The standard seems to address GC as a possibility, a "garbage-collecting implementation", in Memory > Pointer Safety of §iso.20, for example. But, there is no GC offered by the compilers I use. So I am assuming that it's fine allocating once, like the answer says.) – B98 Dec 27 '22 at 18:54
  • I'm not familiar with that quote, but garbage collection in the current C++ standard would violate some fairly fundamental core C++ concepts (unless garbage collection is defined simply as "release memory but don't call any destructors). In any care, garbage collection would have no effect here, since a reference to the `new`ed object remains in scope. – Sam Varshavchik Dec 27 '22 at 19:00