问题描述
请考虑以下代码段:
#include< iostream&
int main(){
std :: string foo;
foo = -1; //为什么编译器不会抱怨这个?
std :: cout<< 1<< std :: endl;
std :: cout<< foo< std :: endl;
std :: cout<< 2< std :: endl;
}
实际输出(ideone.com C ++ 14模式和GCC 4.8。 4):
<无输出>
- 为什么代码段完全编译?
- 注释掉
foo = -1
,我得到正确的stdout(1
和2
)。编译器使用foo = -1;
编译会导致后续cout
失败?
foo = -1;
解析为 std :: string :: operator =(char) code>因为
-1
是 int
和 int
可以,在理论上,可以转换为 char
。
当 int
不表示有效的 char
时。
$ b
更新
C ++ 11标准(强调我):必须查阅您的编译器文档以了解它是否允许 char
对象保存负值,如果是,它如何处理这些对象。
Consider the following code snippet:
#include <iostream>
int main() {
std::string foo;
foo = -1; // why is the compiler not complaining about this?
std::cout << "1" << std::endl;
std::cout << foo << std::endl;
std::cout << "2" << std::endl;
}
Actual output (both ideone.com C++14 mode and GCC 4.8.4):
<no output>
Questions:
- Why did the code snippet compile at all?
- Commenting out
foo = -1
, I get the correct stdout (1
and2
). What has the compiler compiled withfoo = -1;
that causes the subsequentcout
s to fail?
foo = -1;
resolves to std::string::operator=(char)
since -1
is an int
and int
can, in theory, be converted to a char
.
It's not clear to me what the standard says when the int
does not represent a valid char
. It looks like in your implementation, the program crashes.
Update
From the C++11 Standard (emphasis mine):
It appears that you'll have to consult your compiler's documentation to understand whether it allows char
object to hold negative values and, if it does, how does it treat such objects.
这篇关于现在允许为std :: string分配一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!