为什么可以将整数分配给字符串变量?

why an integer can be assigned to a string variable?

在Visual Studio2013年,如果我这样写编译器会报错:

std::string test = 3; 

正在显示:

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

但是,如果我将其更改为:

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

它只是编译!当然会以悲惨的错误告终。

为什么会发生这种情况?

String 可从 char 分配。 int 可隐式转换为 char。

这是因为我们有以下赋值运算符:

basic_string& operator=( CharT ch )

see cppreference.

在这种情况下 int 转换为 char.

这受到 defect report 2372: Assignment from int to std::string 的影响,该问题已作为非缺陷 (NAD) 关闭。它说:

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;

决议是:

This should be addressed by a paper addressed to LEWG