如果我抛出一个字符串字面量我应该捕获什么类型? [英] What type should I catch if I throw a string literal?
问题描述
我在Linux下使用g ++在C ++中编写一个非常简单的应用程序,我试图抛出一些原始字符串作为异常(是的,我知道,它不是一个好的做法)。
I am writing a pretty simple application in C++ using g++ under Linux and I am trying to throw some raw strings as exceptions (yes, I know, its not a good practise).
我有以下代码(简化):
I have the following code (simplified):
int main()
{
try
{
throw "not implemented";
}
catch(std::string &error)
{
cerr<<"Error: "<<error<<endl;
}
catch(char* error)
{
cerr<<"Error: "<<error<<endl;
}
catch(...)
{
cerr<<"Unknown error"<<endl;
}
}
我得到 Unknow错误
。但是如果我静态转换文本字符串到std :: string或char *它打印错误:未实现
如预期。我的问题是:如果我不想使用静态转型,那么我应该捕获什么类型?
And I get Unknow error
on the console. But if I static cast the literal string to either std::string or char* it prints Error: not implemented
as expected. My question is: so what is the type I should catch if I don't want to use static casts?
推荐答案
用 char const *
而不是 char *
来捕获它。 std :: string
或 char *
都不会捕获它。
You need to catch it with char const*
instead of char*
. Neither anything like std::string
nor char*
will catch it.
捕获对于匹配的类型有限制的规则。规范说明(其中cv意味着const / volatile组合或两者都不)。
Catching has restricted rules with regard to what types it match. The spec says (where "cv" means "const/volatile combination" or neither of them).
类型E的异常对象if
A handler is a match for an exception object of type E if
- 处理程序类型为cv T或cv T&和E和T是相同类型(忽略顶级cv限定符),或
- 处理程序类型为cv T或cv T&并且T是E的无歧义的公共基类,或者
-
处理程序类型为cv1 T * cv2,E是可以转换为类型的指针类型处理程序
- The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
- the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of
- 一个标准指针转换(4.10),不涉及到指向私有或受保护或模糊类的指针转换
- 资格转换
$ b b
字符串文字具有类型 char const [N]
,但是抛出一个数组将会衰减数组,并实际抛出一个指向它的第一个元素的指针。所以你不能通过 char *
捕获一个抛出的字符串文字,因为当它匹配时,它需要匹配 char *
到 char const *
,这将抛弃一个const(限定符转换只允许添加 const)。仅当需要专门转换字符串字面量时,才考虑将字符串文字特殊转换为 char *
。
A string literal has type char const[N]
, but throwing an array will decay the array and actually throws a pointer to its first element. So you cannot catch a thrown string literal by a char*
, because at the time it matches, it needs to match the char*
to a char const*
, which would throw away a const (a qualification conversion is only allowed to add const). The special conversion of a string literal to char*
is only considered when you need to convert a string literal specifically.
这篇关于如果我抛出一个字符串字面量我应该捕获什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!