C ++ exception parameter

I have a question regarding the following code snippet that I came across in one of our old 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 called by the value, which means a copy of the text

"this error message

. The catch clause points to a pointer to char as the expected type of exception. Can someone enlighten me why this works? Another issue in this context concerns the memory allocated for the error message. Since the exception type is a pointer to char *, can we assume that the memory for the error message was allocated dynamically on the heap and should be deleted by the user?

Thanks in advance

+3
6

throw . - . , :

(1) " " const char * . . throw. -.

(2) , catch (const char *). char * , ( MSV++, ​​ /Za).

+9

const char*, C, ++.

, .

, , , .

+5

, , . . , :

throw "this is an error message";

, . .

+2

, "ANY STRING" char.

0

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

0
source

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

No, this means that a copy of the pointer is issued.

0
source

Source: https://habr.com/ru/post/1736154/


All Articles