为什么无法将抛出异常的 .what() 方法的输出与字符串进行比较?

Why is it not possible to compare the output of .what() method of thrown exception with a string?

代码无法打印 True,因为由于某种原因比较失败。我不知道它是什么,但是如果我将 e.what() == "Something Bad happened here" 更改为 e.what() == std::string("Something Bad happened here")

它会起作用
#include <iostream>
#include <string>
#include <stdexcept>

int main() {
    try
    {

        throw std::runtime_error("Something Bad happened here");

    }
    catch(std::exception const& e)
    {
        if(e.what() == "Something Bad happened here") {
            std::cout << "True" << "\n";
        }
    } 
}

因为std::exception::what()returns一个const char*,而一个"string literal"是一个const char[N]。它们的运算符 == 对两个指针进行比较。您必须对它们使用 strcmp()

if (strcmp(e.what(), "Something Bad happened here") == 0) // ...

std::string OTOH 有 operator==compare with a const char*

如果你有 C++14 那么你可以得到一个 std::string 没有显式构造函数 s suffix

using namespace std::string_literals;
if (e.what() == "Something Bad happened here"s) // ...

但是当然在比较之前还是需要构造一个std::string,比strcmp

慢一点

在 C++17 中有 std::string_view 构造起来要便宜得多,所以你可以使用这个

using namespace std::literals::string_view_literals;
if (e.what() == "Something Bad happened here"sv) // ...