3

My class has a constexpr constructor which takes a reference to a std::array. When creating a global constexpr constant of my class and passing an immediate array, the constructor gets a null data pointer from the array reference even though the underlying data exists:

class MyClass {
public:
    explicit constexpr MyClass(const std::array<int, 3> &from) {
        assert(from[0] == 1);           // Ok
        assert(from[1] == 2);           // Ok
        assert(from[2] == 3);           // Ok
        assert(from.data() != nullptr); // Compilation halts here
    }
};

static constexpr MyClass constGlobal{std::array{1, 2, 3}};

Requires C++ 17+

Tested on:

MinGW w64 9.0

ARM gcc 12.2

I would expect the data() pointer to exist considering operator[] works perfectly fine.

EDIT:

The data() pointer does exist. This seems to be an issue with GCC not allowing pointer comparison to temporaries. There still exists a related problem which this simplified example attempted to describe (badly).

Here's the root problem.

EDIT:

Looks like this is the likely gcc bug for comparison of addresses of temporaries in constexpr context:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85944

6
  • assert() is for runtime, constexpr needs resolving at compile time. Consider static_assert() instead. Commented Dec 13, 2022 at 19:01
  • what compiler error message you do get? Here gcc is rather clear about not being able to evaluate the assert godbolt.org/z/csneWo546, ie the issue is not that the pointer is a nullptr. Its only the assert that is problematic in the code Commented Dec 13, 2022 at 19:16
  • 1
    Works in MSVC 19.30, see Godbolt Also works on Clang.In the godbolt code I assigned the comparison result to a boolean. That gives a different error on GCC. Commented Dec 13, 2022 at 19:30
  • @Homer512 Setting a flag stored in the class results in this GCC error: "... is not a constant expression because it refers to an incompletely initialized variable" Commented Dec 13, 2022 at 19:45
  • 1
    The issue seems to be with gcc not liking comparing (address-of-temporary-object) with nullptr during constexpr evaluation: <godbolt.org/z/z9bhGjKcd>. Seems like a GCC bug. Vaguely similar question: stackoverflow.com/q/39405241 Commented Dec 13, 2022 at 20:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.