【问题标题】:Why is it not possible to compare the output of .what() method of thrown exception with a string?为什么无法将抛出异常的 .what() 方法的输出与字符串进行比较?
【发布时间】:2021-08-08 14:45:50
【问题描述】:

代码无法打印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";
        }
    } 
}

【问题讨论】:

  • what() 返回const char*,你在比较两个指针

标签: c++ string pointers string-comparison


【解决方案1】:

因为std::exception::what() 返回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) // ...

【讨论】:

  • 在 C++17 中:std::string_view(e.what()) == "foo"e.what() == "foo"sv
  • @HolyBlackCat 是的,我确实看过std::string_view,但我看错了,所以我认为你不能在std::string_viewconst char* 上执行==
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2013-07-28
  • 2011-10-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多