Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why an integer can be assigned to a string variable? [duplicate]

In Visual Studio 2013, the compiler will report error if I write:

std::string test = 3; 

showing:

error C2440: 'initializing' : cannot convert from 'int' to 'std::basic_string,std::allocator>'.

However, if I change it to:

std::string test = "";
test = 3; 

it just compiles! Of course will end up with tragic error.

Why this can happen?

like image 706
athos Avatar asked Mar 06 '23 09:03

athos


1 Answers

This is because we have the following assignment operator:

basic_string& operator=( CharT ch )

see cppreference.

In this case int converts to char.

This was subject to a defect report 2372: Assignment from int to std::string which was closed as not a defect (NAD). It 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.

Ideally the assignment from char could be deprecated and later removed, but as a less intrusive alternative one could consider adding a SFINAEd deleted function template:

template <typename IntT> // enable if is_integral<IntT>::value
basic_string& operator=(IntT) = delete;

and the resolution was:

This should be addressed by a paper addressed to LEWG

like image 171
Shafik Yaghmour Avatar answered Mar 15 '23 17:03

Shafik Yaghmour