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

2024-04-08

代码无法打印True因为由于某种原因比较失败了。我不知道它是什么,但如果我改变它就会起作用e.what() == "Something Bad happened here" to 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";
        }
    } 
}

Because std::exception::what() https://en.cppreference.com/w/cpp/error/exception/what返回一个const char*, and a "string literal" is a const char[N]。操作员==对它们进行两个指针的比较。你必须使用strcmp() on them

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

std::stringOTOH 有一个operator== to 与一个比较const char* https://en.cppreference.com/w/cpp/string/basic_string/compare


如果你有 C++14 那么你可以获得std::string没有显式构造函数s suffix https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s

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

但当然std::string比较之前还是需要先构造一下,可能会比比较慢一点strcmp when SSO https://stackoverflow.com/q/10315041/995714不启动


在 C++17 中有std::string_view https://en.cppreference.com/w/cpp/string/basic_string_view从字符串文字构造起来几乎需要零成本,因此您可以使用它

using namespace std::literals::string_view_literals;
if (e.what() == "Something Bad happened here"sv) // ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么无法将抛出异常的 .what() 方法的输出与字符串进行比较? [复制] 的相关文章

随机推荐