c ++异常参数 [英] c++ exception parameter
问题描述
我有一个关于我在一个旧版图书馆遇到的以下代码段的问题。
try
{
throwthis is a error message;
}
catch(char * error)
{
cout< 发生异常:<错误< endl
}
我在这种情况下的行为的理解是,错误信息被抛出by value,which means a copy of the text
这是一个错误讯息
。 catch子句指定一个指向char的指针作为预期的异常类型。有些人可以启发我,为什么这样工作?在此上下文中的另一个问题涉及为错误消息分配的内存。因为异常类型是指向char *的指针,可以假定错误消息的内存已经在堆上动态分配,并且必须由用户删除?
提前感谢
在 throw
中,上下文数组衰减到指针。而字符串literal是一个字符数组。这意味着:
(1)在这种情况下,由值抛出是一个
指向现有字符串文字的指针。不会创建字符串文字的副本。此 throw
不会分配额外的内存。
catch(const char *)
处理程序。你的 char *
处理程序不会捕获它,除非你的编译器有一个bug(这是一个已知的MSVC ++编译器的持久性错误,甚至不是由 / Za
选项)。 I have a question regarding the following code snippet I came across in one of our older libraries.
try
{
throw "this is an error message";
}
catch( char* error )
{
cout << "an exception occured: " << error << endl;
}
My understanding of the behavior in this case is, that the error message is thrown by value, which means a copy of the text
"this is an error message"
is thrown. The catch clause specifies a pointer to char as expected type of exception. Can some enlighten me, why this works? Another question in this context concerns the memory allocated for the error message. Since the exception type is pointer to char* one could assume, that the memory for the error message has been allocated dynamically on the heap and has to be deleted by the user?
Thanks in advance
In throw
context arrays decay to pointers. And string literal is an array of characters. This means that:
(1) What is "thrown by value" in this case is a const char *
pointer to the existing string literal. No copy of string literal is made. No additional memory is allocated by this throw
. There's no need to deallocate anything.
(2) In order to catch this exception you need a catch (const char *)
handler. Your char *
handler will not catch it, unless your compiler has a bug in it (this is a known persistent bug in MSVC++ compilers, which is not even fixed by /Za
option).
这篇关于c ++异常参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!