【问题标题】:what type-conversion is taking place when a boolean value used to construct a string object?当布尔值用于构造字符串对象时,会发生什么类型转换?
【发布时间】:2011-06-15 15:07:26
【问题描述】:

在我的代码中,有一个错字:在初始化std::string 对象时,我没有使用"false",而是输入了false(这是一个bool)。现在这并没有报告任何编译错误。但稍后在我的代码中,当使用这个字符串对象时,我在运行时得到std::logic_error。谁能解释一下,为什么在这种情况下允许构造(否则我会收到编译错误并在那里发现问题)?

这是一个小sn-p-

#include <iostream>

int main ()
{

   std::string str = false;

   std::cout << str << "\n";

}

运行时得到的 o/p -

xhdrdevl8@~/MYBACKUP=>g++ -o test_string -g test_string.cxx

xhdrdevl8@~/MYBACKUP=>./test_string

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct NULL not valid
Aborted

【问题讨论】:

    标签: c++ string constructor type-conversion


    【解决方案1】:

    std::string 有一个构造函数,它将const char* 接收到一个以空字符结尾的字符串。

    false可以用作空指针常量,因为它是一个值为0的整型常量表达式,所以使用了这个std::string构造函数。

    将空指针传递给此构造函数会产生未定义的行为。您的标准库实现通过生成 logic_error 异常来帮助您,以通知您通过传递一个空指针来通知您违反了 std::string 构造函数的约束。其他实现可能没有那么有用(您可能会立即崩溃或数据损坏或谁知道)。

    【讨论】:

    • 好的。但这不应该导致编译时错误吗? (而不是稍后在运行时捕获错误)
    • @anindita: 否。false 可用作空指针常量(就像 0 是或 NULL#include &lt;cstddef&gt; 一样)并且空指针常量可以用作const char*,因此可以使用采用 const char*std::string 构造函数。
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 2016-02-27
    • 2018-04-06
    • 2020-12-26
    • 2018-12-28
    • 2010-12-05
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多