https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111737
Bug ID: 111737 Summary: Object holding a pointer to an uninitialized c-array not usable in a constant expression Product: gcc Version: 13.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: benoit.labrique at endress dot com Target Milestone: --- Following code does not compile (see details below) as soon as there is an indirection, in this case the function MakeBuffer(). This kind of construct is very common in the embedded world, where dynamic memory allocation is not permitted. As in the code example, buffers of different size can be passed to more generic functionality via a reference to the base class "Collection", which is buffer-size agnostic. // Compiled with -O2 -std=c++17 class Collection { protected: constexpr Collection(void * iBuffer) : m_buffer(iBuffer) { } protected: void * m_buffer = nullptr; }; class Buffer final : public Collection { public: explicit constexpr Buffer() : Collection(m_buffer), m_buffer{0} // gcc doesn't like that m_buffer is used before it is initialized. Using std::array instead won't work at all. { } private: int m_buffer[1]; }; namespace { inline constexpr auto MakeBuffer() { return Buffer(); // C++17: shall definitively perform copy elision } constexpr Buffer VIA_MAKE_BUFFER = MakeBuffer(); // Only gcc has a problem with, neither clang nor msvc constexpr Buffer VIA_BUFFER_CONSTRUCTOR = Buffer(); // Why is it now OK for gcc here? } int main() { constexpr auto a = VIA_MAKE_BUFFER; constexpr auto b = VIA_BUFFER_CONSTRUCTOR; return 0; } https://godbolt.org/z/erPsooP4b Compiling this code issues (ARM GCC 13.2 (or earlier)): <source>: In function 'int main()': <source>:38:24: error: the value of '{anonymous}::VIA_MAKE_BUFFER' is not usable in a constant expression 38 | constexpr auto a = VIA_MAKE_BUFFER; | ^~~~~~~~~~~~~~~ <source>:32:22: note: '{anonymous}::VIA_MAKE_BUFFER' used in its own initializer 32 | constexpr Buffer VIA_MAKE_BUFFER = MakeBuffer(); // Only gcc has a problem with, neither clang nor msvc | ^~~~~~~~~~~~~~~ Alternatively: on x86-64 GCC 13.2 (or earlier): <source>:32:51: error: 'Buffer{Collection{((void*)(&<anonymous>.Buffer::m_buffer))}, int [1]{0}}' is not a constant expression 32 | constexpr Buffer VIA_MAKE_BUFFER = MakeBuffer(); // Only gcc has a problem with, neither clang nor msvc |