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

            Bug ID: 69995
           Summary: [C++14] Invalid result when evaluating constexpr
                    function
           Product: gcc
           Version: 6.0
            Status: UNCONFIRMED
          Severity: major
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ldionne.2 at gmail dot com
  Target Milestone: ---

The following code triggers a runtime assertion:

------------------------------------------------------------------------------
#include <cassert>

#define CONSTEXPR constexpr

template <typename T, unsigned long Size>
struct array {
    T elems_[Size];

    constexpr T const& operator[](unsigned long n) const
    { return elems_[n]; }

    constexpr T& operator[](unsigned long n)
    { return elems_[n]; }
};

template <typename T>
CONSTEXPR void my_swap(T& a, T& b) {
    T tmp = a;
    a = b;
    b = tmp;
}

CONSTEXPR auto rotate2() {
    array<array<int, 2>, 2> result{};
    array<int, 2> a{{0, 1}};

    result[0] = a;
    my_swap(a[0], a[1]);
    result[1] = a;

    return result;
}

int main() {
    CONSTEXPR auto indices = rotate2();
    assert(indices[0][0] == 0);
    assert(indices[0][1] == 1);
    assert(indices[1][0] == 1);
    assert(indices[1][1] == 0);
}
------------------------------------------------------------------------------

The fun thing is that #defining CONSTEXPR to nothing makes the code work again.
So GCC's constexpr evaluation seems to be broken in this case, in a way that
can lead to _runtime_ errors.

Live example: http://melpon.org/wandbox/permlink/PPpwDHbk5tYVlNWI

Reply via email to