现在允许为std :: string分配一个数字? [英] Assigning a number to std::string is now allowed?

查看:142
本文介绍了现在允许为std :: string分配一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

  #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):

<无输出> 




  1. 为什么代码段完全编译?

  2. 注释掉 foo = -1 ,我得到正确的stdout( 1 2 )。编译器使用 foo = -1; 编译会导致后续 cout 失败?


解决方案

  foo = -1; 

解析为 std :: string :: operator =(char) code>因为 -1 int int 可以,在理论上,可以转换为 char



int 不表示有效的 char 时。


$ b

更新

C ++ 11标准(强调我):


3.9.1基本类型 b
$ b

1声明为字符( char )的对象应足够大以存储实现的基本字符集的任何成员。如果该集合中的字符存储在字符对象中,则该字符
对象的整数值等于该字符的单字符文字形式的值。 它是由实现定义的,是否一个char对象可以保存负值。


必须查阅您的编译器文档以了解它是否允许 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:

  1. Why did the code snippet compile at all?
  2. Commenting out foo = -1, I get the correct stdout (1 and 2). What has the compiler compiled with foo = -1; that causes the subsequent couts 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):

3.9.1 Fundamental types

1 Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values.

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分配一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆