Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ explicit conversion really that bad?

Tags:

c++

casting

My knowledge of C++ at this point is more academic than anything else. In all my reading thus far, the use of explicit conversion with named casts (const_cast, static_cast, reinterpret_cast, dynamic_cast) has come with a big warning label (and it's easy to see why) that implies that explicit conversion is symptomatic of bad design and should only be used as a last resort in desperate circumstances. So, I have to ask:

Is explicit conversion with named casts really just jury rigging code or is there a more graceful and positive application to this feature? Is there a good example of the latter?

like image 339
LoudNPossiblyWrong Avatar asked Jun 15 '10 13:06

LoudNPossiblyWrong


2 Answers

There're cases when you just can't go without it. Like this one. The problem there is that you have multiple inheritance and need to convert this pointer to void* while ensuring that the pointer that goes into void* will still point to the right subobject of the current object. Using an explicit cast is the only way to achieve that.

There's an opinion that if you can't go without a cast you have bad design. I can't agree with this completely - different situations are possible, including one mentioned above, but perhaps if you need to use explicit casts too often you really have bad design.

like image 126
sharptooth Avatar answered Nov 15 '22 21:11

sharptooth


There are situations when you can't really avoid explicit casts. Especially when interacting with C libraries or badly designed C++ libraries (like the COM library sharptooth used as examples).

In general, the use of explicit casts IS a red herring. It does not necessarily means bad code, but it does attract attention to a potential dangerous use.

However you should not throw the 4 casts in the same bag: static_cast and dynamic_cast are frequently used for up-casting (from Base to Derived) or for navigating between related types. Their occurrence in the code is pretty normal (indeed it's difficult to write a Visitor Pattern without either).

On the other hand, the use of const_cast and reinterpret_cast is much more dangerous.

  • using const_cast to try and modify a read-only object is undefined behavior (thanks to James McNellis for correction)
  • reinterpret_cast is normally only used to deal with raw memory (allocators)

They have their use, of course, but should not be encountered in normal code. For dealing with external or C APIs they might be necessary though.

At least that's my opinion.

like image 38
Matthieu M. Avatar answered Nov 15 '22 19:11

Matthieu M.