cast still is in use when it dangerous

Possible Duplicate:
Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job?

I have been suggested that i should not use reinterpret_cast or const_cast in case of pointer to pointer conversion. Only dynamic_cast should be used.Because other cast can create problem in future. So my question is why not reinterpret_cast or other cast which is dangerous has been removed from c++ standard.


Because there are times when you need a cast which does what reinterpret_cast does. As for dynamic_cast , I almost never use this cast; that's only for casting from a parent type to a more derived type. Most of the time I can prove which child type I'm working with, and I use static_cast . I also use static_cast for compile time type conversions, for example from signed to unsigned integers.

static_cast , not dynamic_cast , is the most common kind of cast. If your design relies on dynamic_cast too heavily, that's a code smell indicating your class hierarchy violates LSP in most cases.


They are dangerous but sometimes you need them.

C++ is not know for removing constructs that are dangerous to the new user. We will let you run with those scissors (while eating cake).

What makes them good is that the dangerous code sticks out so it is easy to spot. So when people do code reviews they can quickly spot the stuff that is dangerous and add a little scrutiny more checking.


In the real world, you frequently have to cast pointers in ways the compiler/runtime can't validate. For example, in pthreads you pass a void* to the new thread's start routine. Sometimes that arg is actually a class? The compiler has no way to tell. It's one of those "real life" issues.

Incidentally I find myself using dynamic_cast infrequently. My main use for is has been exception type scraping in catch blocks.

链接地址: http://www.djcxy.com/p/28754.html

上一篇: C ++

下一篇: 当它危险的时候仍然在使用