C++ runtime_exception字符串 + 整数

C++ runtime_exception with string + integer

本文关键字:整数 字符串 exception runtime C++      更新时间:2023-10-16

>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));

runtime_error的定义之一需要const char*,这就是你传递它的内容。这部分代码:

"abcdefghijklmnopqrstuvq"+12

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

执行此操作时:

"abcdefghijklmnopqrstuvq"+std::to_string(12)

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

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

向其添加12会给出一个指针12前方位置,即"mnopqrstuvq"