Why does the following code compile? It compiles and runs fine with clang and prints first.
But, I believe the correct behavior should be to complain and issue a proper error.
#include <iostream>
#include <string>
int main()
{
std::string s{ "first", "second" };
std::cout << s << std::endl;
}
This question is inspired by this.
std::string
has a template constructor that takes two iterators. When you pass string literals, they will decay to char const*
, which qualifies as an iterator. However, since those pointers do not form a valid range, you have undefined behavior.
This is undefined behavior.
This is invoking a constructor of std::string
that accepts two iterators, the beginning and the ending iterator value. Because both initialization parameters have the same type, they are interpreted as a pair of iterators, and match this particular overloaded constructor.
The values of the character pointers are interpreted as beginning/ending iterator values. It just happens to work with clang, but with gcc this throws an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With