Shafik Yaghmour

Compiler Engineer at Intel. This is a personal blog. The opinions stated here are my own, not those of my company.

This program is well-formed. We can see from cppreference we have

basic_string& operator=( CharT ch );

and int is converted to char.

This was subject of a LWG defect report 2372: Assignment from int to std::string which was closed NAD and which says:

The following code works in C++:

int i = 300;
std::string threeHundred;
threeHundred = i;

“Works” == “Compiles and doesn’t have an undefined behavior”. But it may not be obvious and in fact misleading what it does. This assignment converts an int to char and then uses string’s assignment from char. While the assignment from char can be considered a feature, being able to assign from an int looks like a safety gap. Someone may believe C++ works like “dynamically typed” languages and expect a lexical conversion to take place.

There where several good tweets in reply to this poll:

and