2

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

  • `assert()` is for runtime, `constexpr` needs resolving at compile time. Consider `static_assert()` instead. – πάντα ῥεῖ Dec 13 '22 at 19:01
  • what compiler error message you do get? Here gcc is rather clear about not being able to evaluate the assert https://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 – 463035818_is_not_an_ai Dec 13 '22 at 19:16
  • 1
    Works in MSVC 19.30, see [Godbolt](https://godbolt.org/z/xs6hGnsE1) Also works on Clang.In the godbolt code I assigned the comparison result to a boolean. That gives a different error on GCC. – Homer512 Dec 13 '22 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" – Lukas Vozenilek Dec 13 '22 at 19:45
  • 1
    The issue seems to be with gcc not liking comparing (address-of-temporary-object) with nullptr during constexpr evaluation: . Seems like a GCC bug. Vaguely similar question: https://stackoverflow.com/q/39405241 – Artyer Dec 13 '22 at 20:50
  • @Artyer Looks like this is still an issue and is the cause of the assert failing to compile. There still exists a related issue that I have spooled off into it's own question. See edit for link. – Lukas Vozenilek Dec 13 '22 at 22:19

0 Answers0