CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Clarification for gsl::dyn_array design

Open JordanMaples opened this issue 5 years ago • 5 comments

There's been a request for the Microsoft GSL to implement dyn_array (microsoft/gsl#890). Would the editors mind providing clarification on it's design and priority.

Thanks.

JordanMaples avatar Jun 03 '20 22:06 JordanMaples

Editors call: @JordanMaples, could you please write a short specification and post it here for us to review? The key is that allocation only happens at construction, so that subsequent push_back calls (up to the limit) do not invalidate any pointers into the array.

hsutter avatar Jun 04 '20 18:06 hsutter

Editors call: Relatedly, we would also like to see a gsl::stack_array that is stack-only and uses alloca or the equivalent. Note this could require minor compiler magic rather than be a purely library feature. This type would be a safer version of alloca and C99 VLAs.

hsutter avatar Jun 04 '20 18:06 hsutter

The Google Abseil project has, and I quote, "a good replacement for non-standard and deprecated uses of alloca() and variable length arrays". They call it FixedArray. Is this what you are looking for?

FixedArray: https://chromium.googlesource.com/external/github.com/abseil/abseil-cpp/+/HEAD/absl/container/fixed_array.h

HFriberg avatar Jun 29 '20 12:06 HFriberg

If I understand correctly, the Absail FixedArray is not an alternative to stack_array for some embedded systems uses where they don't accept spillover to heap - because heap allocation is banned.

BjarneStroustrup avatar Aug 06 '20 15:08 BjarneStroustrup

For completeness, their solution (as I understand it) is to have a compile-time sized stack buffer (default 256 bytes): alignas(StorageElement) char buff_[sizeof(StorageElement[inline_elements])];

from which they cut out the runtime requested array size (with spillover to heap when buffer is insufficient). If heap allocation is banned, however, I do not see any appropriate fallback behavior. Neither increasing the stack buffer size or throwing runtime exceptions seems like a good options to stop spillover. So I agree with @BjarneStroustrup that this solution is not for embedded systems.

HFriberg avatar Aug 11 '20 07:08 HFriberg