Fijoy Vadakkumpadan
Fijoy Vadakkumpadan

Reputation: 668

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

Upvotes: 4

Views: 3327

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

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.

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 5

Related Questions