【问题标题】:C++ runtime_exception with string + integer字符串+整数的C++ runtime_exception
【发布时间】:2020-05-19 14:55:31
【问题描述】:

在 C++ 中,我会抛出如下所示的运行时异常,

throw std::runtime_error("abcdefghijklmnopqrstuvq"+12);

抛出的异常没有前几个字符。

terminate called after throwing an instance of 'std::runtime_error'
  what():  mnopqrstuvq
Aborted (core dumped)

有人可以解释这种行为吗?

如果我使用下面的 stmt 抛出异常,一切都会正常

throw std::runtime_error("abcdefghijklmnopqrstuvq"+std::to_string(12));

【问题讨论】:

  • "abcdefghijklmnopqrstuvq"+12 应该从字符串中删除最火的 12 个字符,因为它是指针递增操作。它相当于获取字符串文字的地址并在其上加 12。

标签: c++ string exception integer


【解决方案1】:

runtime_error 的定义之一采用const char*,这就是您要传递的内容。本段代码:

"abcdefghijklmnopqrstuvq"+12

获取指向此const char* 的指针并将其递增12(恰好是字符串中的m)。

当你这样做时:

"abcdefghijklmnopqrstuvq"+std::to_string(12)

您正在调用operator+(const char*, std::string) 函数,该函数返回一个字符串(特别是"abc...12"),从而调用runtime_error(std::string&) 声明。

【讨论】:

    【解决方案2】:

    文字"abcdefghijklmnopqrstuvq" 实际上只是一个指向char const 数组的指针。

    12 添加到它会得到一个指针12 前面的位置,即"mnopqrstuvq"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多