Why does this code compile (C++11) without a type mismatch error?
Asked Answered
E

1

45
std::vector<char> p = {"abc", "def"};

"abc" and "def" are not char, why doesn't the compiler give me an error about this type mismatch?

Engvall answered 28/1, 2018 at 1:1 Comment(0)
K
57

You're not calling vector's constructor that takes an initializer_list<char>. That constructor is not viable because, as you said, you're not passing a list of chars.

But vector also has a constructor that takes iterators to a range of elements.

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

Unfortunately, this constructor matches because the two arguments will each implicitly convert to char const *. But your code has undefined behavior because the begin and end iterators being passed to the constructor are not a valid range.

Kironde answered 28/1, 2018 at 1:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.