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

            Bug ID: 104348
           Summary: Incorrect sorting in constexpr constructor
           Product: gcc
           Version: 10.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: asorenji at gmail dot com
  Target Milestone: ---

I have simple test code, that just sorting array of string_view wrapped in
another class. This array contain list of "1","2","3","4","5","6","7","8"
values and remains unchanged if code executed in runtime. Well, it's already
sorted from beginning. But if constexpr used and code executed it compile time,
I get 17256348 instead of 12345678. For very strangle reason, bug appear in
constexpr variable constructor, but disappear in constinit variable
constructor.

g++ --version - g++ (Debian 10.2.1-6) 10.2.1 20210110
Compile options - g++ -std=c++20 -Wall -Wextra main.cpp -o test
Code:

#include<string_view>
#include<algorithm>
#include<iostream>

class Test
{
public:
    //for some reason, bug don't appear if std::string_view not wrapped in
another class
    class Value
    {
    public:
        constexpr Value(const char*str):data(str){}
        constexpr bool operator<(const Value&value)const{return
data<value.data;}

        std::string_view data;
    };

    constexpr Test()
    {
        //no bug if std::sort used
        //std::sort(array,array+8);
        std::make_heap(array,array+8);
        std::sort_heap(array,array+8);
    }

    Value array[8]={"1","2","3","4","5","6","7","8"};
};

int main()
{
    //product 12345678
    //Test test;

    //also word well
    //static constinit Test test;

    //Bug. Product 17256348 instead of 12345678
    static constexpr Test test;

    for(auto&value:test.array)
        std::cout<<value.data;
    return 0;
}

Reply via email to