Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Incorrect behavior of std::string initialization

Tags:

c++

string

stl

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.

like image 458
Eissa N. Avatar asked May 15 '16 02:05

Eissa N.


2 Answers

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.

like image 169
Benjamin Lindley Avatar answered Sep 28 '22 08:09

Benjamin Lindley


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.

like image 34
Sam Varshavchik Avatar answered Sep 28 '22 09:09

Sam Varshavchik