ebi
ebi

Reputation: 501

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

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?

Upvotes: 45

Views: 1776

Answers (1)

Praetorian
Praetorian

Reputation: 109119

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.

Upvotes: 57

Related Questions