Search code examples
c++portabilityinitializer-listcompound-literals

A portable C++ alternative to compound literals that is guaranteed to be free of heap allocation


C99 compound literals are not supported in C++. In many cases, list intialization provides an excellent alternative. However, they are not guaranteed not to heap-allocate memory.

Are there any convenient and portable alternatives for C++ code that needs to work entirely without heap allocations?


Solution

  • As the answers on the linked question indicate, since C++14 the compiler cannot heap-allocate an initializer list. Moreover, even pre-C++14 compilers won't heap allocate initializer lists, as there's absolutely no reason to do so (and plenty of reasons not to).