static_cast<>

A

alg

I read somewhere that static_cast<> is not safe, sometimes fatal. Could
someone tell me why it is still around and when it should be used in
general? When will it be unsafe to use it?

Thanks for your help!
 
D

David White

alg said:
I read somewhere that static_cast<> is not safe, sometimes fatal. Could
someone tell me why it is still around and when it should be used in
general?

An example of a safe usage is downcasting a base-class pointer to a
derived-class pointer when you absolutely _know_ that the pointer will
really point to an instance of the derived class after the cast. You might
choose static_cast over dynamic_cast in such as case for greater execution
speed. (Whether you could have avoided the downcast altogether is another
matter. Downcasts are distasteful.)
When will it be unsafe to use it?

When there is no sensible conversion to the destination type. If you have a
Shape* that you think points to what was created as a Rectangle, then it
would be unsafe to static_cast it to an Ellipse*, for example. Since
programmers generally don't do such things deliberately, unsafe usage would
nearly always result from the programmer's misunderstanding of what the
object can be safely converted to. In this respect static_cast is unsafe
because the programmer is saying to the compiler, "trust me", but now and
then that trust is misplaced, and a bug or potential bug is the result.

DW
 
A

alg

David White said:
An example of a safe usage is downcasting a base-class pointer to a
derived-class pointer when you absolutely _know_ that the pointer will
really point to an instance of the derived class after the cast. You might
choose static_cast over dynamic_cast in such as case for greater execution
speed. (Whether you could have avoided the downcast altogether is another
matter. Downcasts are distasteful.)
Thanks, David!

How do "you absolutely _know_ that the pointer will really point to an
instance of the derived class after the cast"? By checking the return value
to see if it's NULL or not?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top