Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Win32 code in your modern C++ app, should you use proper casting?

For example the following cast can be found littered throughout the MSDN documentation:

(LPTSTR)&lpMsgBuf

Should I bother converting that to:

static_cast<LPTSTR>(&lpMsgBuf);

Or should I just leave all the idiomatic C-esque Win32 portions as they are typically found in the docs, and save the more idiomatic C++ style/usage for the rest of my code?

like image 205
ApplePieIsGood Avatar asked Nov 28 '22 12:11

ApplePieIsGood


1 Answers

New style casts were introduced for a reason: they're safer, more explanatory/self-commenting, easier to see, and easier to grep for.

So use them.

By more explanatory, we mean that you can't just cast to something, you have to say why you're casting (I'm casting in an inheritance hierarchy (dynamic_cast), my cast is implementation defined and possibly not portable (reinterpret_cast), I'm casting away constness (const_cast), etc.).

They're purposefully long and ugly so that the cast jumps out at the reader (and to discourage a programming style that employs too much casting).

They're safer because, e.g., you can't cast away constness without explicitly doing that.

like image 181
tpdi Avatar answered Dec 05 '22 06:12

tpdi