Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a reinterpret_cast itself cause an exception?

Suppose I have a class called A, and a void pointer vp. Can the following ever cause an exception?

A *ap = reinterpret_cast<A*>(vp);

Thank you, Fijoy

like image 326
Fijoy Vadakkumpadan Avatar asked Dec 19 '22 17:12

Fijoy Vadakkumpadan


2 Answers

No, neither a reinterpret_cast<T> nor its C-style cast equivalent perform any checking, so they cannot by themselves cause an exception. Obviously, since both constructs are about as unsafe as it gets, dereferencing the result pointer ap could cause undefined behavior.

like image 194
Sergey Kalinichenko Avatar answered Dec 24 '22 02:12

Sergey Kalinichenko


Assuming (which you can in your case since it's of type void*) the expression vp doesn't throw an exception (it could do if it was an object of a type that had a hand-crafted conversion operator that threw an exception), then

A *ap = reinterpret_cast<A*>(vp);

will not itself throw an exception.

dereferencing ap could cause an exception to be thrown however.

like image 34
Bathsheba Avatar answered Dec 24 '22 01:12

Bathsheba