简体   繁体   中英

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?

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).

If your program works entirely without heap allocations, adding list initialization will be fine and will not cause heap memory allocation.

The cases where iist initialization might cause heap allocation are the cases where your objects already use heap memory, for example std::list. You certainly don't use those, if you are heap free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM