
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct. The mere typing of it should cause you to feel VERY uncomfortable. like a Siren with Red Flashing Lights in your code.

but the presence of a reinterpret_cast is On the other hand, it's easy to search for "static_cast(pSomething)
#Scala convert string to long full#
It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. In complex expressions it can be very hard to see C-style casts. The second problem is that the C-style casts are too hard to locate. POther = (CMyOtherStuff*)(pSomething) // No compiler error.Īs you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved. As we said before, conversions between String and Long are very similar to what we did with Intin the previous section: If we were to attempt to run 42a. POther = static_cast(pSomething) // Compiler error: Can't convert However, let's see this almost identical code: CMyOtherStuff *pOther PMyObject = (CDerivedClass*)(pSomething) // Same as static_cast PMyObject = static_cast(pSomething) // Safe as long as we checked Now, these two are compiled the same way: CDerivedClass *pMyObject Let's assume these: class CDerivedClass : public CMyBase
#Scala convert string to long code#
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is". A dynamic_cast() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).Ī reinterpret_cast() (or a const_cast()) on the other hand is always dangerous. The only time it's a bit risky is when you cast down to an inherited class you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object).

There is a valid conversion in the language, or an appropriate constructor that makes it possible. These four things are completely different.Ī static_cast() is usually safe. The main reason is that classic C casts make no distinction between what we call static_cast(), reinterpret_cast(), const_cast(), and dynamic_cast().
