简体   繁体   English

为什么 string 在这里不起作用而 char const* 可以?

[英]Why does string not work here while char const* does?

Why does string not work here when I catch an error, and char const* does?为什么当我发现错误时string在这里不起作用,而char const*却起作用? What is the difference between the two?两者有什么区别?

try {
    throw "connection fail";

} catch( string e ) {
    if(e == "connection fail") {
        std::cout << "caught: " << e << std::endl;
    }
}

You're not throwing a std::string, so you can't catch one.你没有扔一个 std::string,所以你抓不到一个。

Why is that not a string?为什么不是字符串?

Because in C++, the perfidiously-misnamed string literals (that's what "abc" is) are not strings.因为在 C++ 中,错误命名的字符串文字(这就是"abc" )不是字符串。 A string literal allocates some static storage for the contents of the string, and evaluates as a const char (&)[N] type, ie a reference to an array of characters of a given fixed length.字符串文字为字符串的内容分配了一些 static 存储空间,并评估为const char (&)[N]类型,即对给定固定长度的字符数组的引用。 In most contexts, that reference decays to a const char * , which is a pointer to a const char, and has nothing to do with strings in any sensible interpretation of the term "string".在大多数情况下,该引用衰减为const char * ,它是指向 const char 的指针,并且在对术语“字符串”的任何合理解释中都与字符串无关。 This is an unfortunate legacy of C, where there were no strings either, and you passed a "string" by passing a pointer to the first character of a string, with the implicit assumption that the string has to be '\0' -terminated and of course couldn't contain NUL's ( '\0' ) since they were indistinguishable from a terminator.这是 C 的不幸遗留问题,其中也没有字符串,并且您通过传递指向字符串的第一个字符的指针来传递“字符串”,隐含假设字符串必须以'\0'结尾当然不能包含 NUL ( '\0' ),因为它们终止符无法区分。

To create a string, you must be explicit about it: throw std::string("foo bar baz");要创建字符串,您必须明确说明: throw std::string("foo bar baz");

this should work这应该工作

try {
    throw (std::string)"connection fail";

} catch( string e ) {
    if(e == "connection fail") {
        std::cout << "caught: " << e << std::endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM