[Bug c++/108195] New: Incorrect implicit conversion when assigning initializer_list to std::vector

gcc-bugzilla at al42and dot me gcc-bugzilla@gcc.gnu.org
Wed Dec 21 17:48:15 GMT 2022


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

            Bug ID: 108195
           Summary: Incorrect implicit conversion when assigning
                    initializer_list to std::vector
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gcc-bugzilla at al42and dot me
  Target Milestone: ---

The following code compiles fine with Clang 15 and GCC 12 and outputs "3" when
run.

With GCC 13, it produces a warning about narrowing conversion and constructs a
vector of length 2.

$ cat test.cpp 
#include <iostream>
#include <vector>

struct S
{
    S(bool) {}
};

int main()
{
    std::vector<S> v = { true, false, true };
    std::cout << v.size() << std::endl;
}

$ g++ -std=c++17 test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:11:44: warning: narrowing conversion of ‘(((void)const bool [3]{true,
false, true}), ((const bool*)(&<anonymous>)))’ from ‘const bool*’ to ‘bool’
[-Wnarrowing]
   11 |     std::vector<S> v = { true, false, true };
      |                                            ^
test.cpp:11:44: warning: narrowing conversion of ‘(((const
bool*)(&<anonymous>)) + 3)’ from ‘const bool*’ to ‘bool’ [-Wnarrowing]

$ ./test
2

Using a constructor instead of the assignment avoids this problem:
std::vector<S> v { true, false, true }; // works fine

Creating an initializer_list separately is also ok:
std::initializer_list<S> il = { true, false, true };
std::vector<S>           v  = il; // no problem here, vector has three elements

Tested with GCC fdc7469cf597ec11229ddfc3e9c7a06f3d0fba9d. Bisection points to
d081807d8d70e3e87eae41e1560e54d503f4d465 (PR105838).


More information about the Gcc-bugs mailing list