开发者

c++ exception parameter

开发者 https://www.devze.com 2022-12-22 15:12 出处:网络
I have a question regarding the following code snippet I came across in one of our older libraries. try

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 qu开发者_JAVA百科estion 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).


It should actually catch const char* because that is the type of string constants both in C and C++.

It is passed by value, but by the value of the pointer.

It shouldn't be deleted, because as you can clearly see from the code, there is no dynamic allocation.


Its not the string that is being thrown, but the pointer to the string. You do not have to delete it. The pointer points to a string literal, instantiated at the point of the call:

throw "this is an error message";

This string is not allocated on the stack, but statically. You could think of it as a compile time constant.


This works because the default type of "ANY STRING" is a pointer to a static char array.


I think you are almost right and the message is thrown by value. But not by char[XXX]. It's thrown by char*. And data is stored in static memory.


My understanding of the behavior in this case is, that the error message is thrown by value, which means a copy of the text [...] is thrown.

No, it means a copy of the pointer is thrown.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号