c++ - 现在允许为 std::string 分配一个数字吗?

标签 c++ gcc

考虑以下代码片段:

#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;
}

实际输出(ideone.com C++14模式和GCC 4.8.4):

<no output>

问题:

  1. 为什么代码片段会编译?
  2. 注释掉 foo = -1,我得到了正确的标准输出(12)。编译器使用 foo = -1; 编译导致后续 cout 失败的原因是什么?

最佳答案

foo = -1;

解析为 std::string::operator=(char)自从 -1intint理论上可以转换为 char .

我不清楚标准在 int 时的含义。不代表有效的 char .看起来在您的实现中,程序崩溃了。

更新

来自 C++11 标准(重点是我的):

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.

看来您必须查阅编译器的文档才能了解它是否允许 char对象来保存负值,如果是,它如何处理这些对象。

关于c++ - 现在允许为 std::string 分配一个数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37202036/

相关文章:

c++ - 学校二进制转十进制练习

c++ - 为什么 C++ 不使用 std::nested_exception 来允许从析构函数中抛出?

c++ - gcc 支持 cbegin 和 cend 方法

c++ - 设置跳转/长跳转 : Why is this throwing a segfault?

android - Cocos2d-x 应用程序无法为 Android 编译

c++ - 用 C++ 编写类时遇到问题;未声明的标识符

c++ - 检查输入是C++中的数字还是字符串

c - 交叉编译时如何使用外部库?

c - C语言中如何知道未知类型变量的数据类型?

c - 用于大小分析的 GCC 工具?