Eissa N.
Eissa N.

Reputation: 1725

C++ Incorrect behavior of std::string initialization

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.

Upvotes: 6

Views: 315

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

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.

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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.

Upvotes: 8

Related Questions