Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused on C++ casting

Tags:

c++

casting

I have been reading a lot about C++ casting and I am starting to get confused because I have always used C style casting.

I have read that C style casting should be avoided in C++ and that reinterpret_cast is very very dangerous and should not be used whenever there is an alternative. On the contrary to not using reinterpret_cast, I have seen it used many times on MSDN in their sample code. This leads me to ask my first question, when is it ok to use reinterpret_cast?

For example:

LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
   switch (Msg)
   {
      case WM_CREATE:
      {
          LPCREATESTRUCT lpCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); 
          return 0;
      }
   }

   ...
}

If that is not ok, then how would I cast the LPARAM value to a pointer using only static, dynamic, and/or const casting?

Also: If reinterpret_cast is not portable, how would I rewrite it to be portable (for good practice)

like image 591
Marlon Avatar asked Feb 27 '10 00:02

Marlon


People also ask

What happens when casting in C?

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.

What is type conversion and type casting in C explain in brief?

In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler. 2. Type casting can be applied to compatible data types as well as incompatible data types.


1 Answers

Using reinterpret_cast is acceptable if you know that the pointer was originally of the destination type. Any other use is taking advantage of implementation-dependent behavior, although in many cases this is necessary and useful, such as casting a pointer to a structure into a pointer to bytes so that it can be serialized.

It is considered dangerous because it does no checking, either at compile-time or at runtime. If you make a mistake, it can and will crash and burn horribly, and be difficult to debug. You are essentially telling the compiler "I know better than you what this actually is, so just compile the code and let me worry about the consequences."

like image 112
MikeP Avatar answered Nov 13 '22 13:11

MikeP