Difference between revisions of "Cpp"

From HoerupWiki
Jump to: navigation, search
(C++ casting operators)
(C++ casting operators)
Line 31: Line 31:
  
 
<code>
 
<code>
reinteroret_cast<void**>(&pSome)
+
reinterpret_cast<void**>(&pSome)
 
</code>
 
</code>
  
 
The syntax of the other C++ casting operators follows the same pattern as reinterpret_cast.
 
The syntax of the other C++ casting operators follows the same pattern as reinterpret_cast.

Revision as of 12:06, 18 June 2006

Der er mange gode artikler om c++ på informit.com

Hvis at du har brug for noget generic funktionality som måske ikke lige ligger i STL er det værd at tage et kig på boost som er en samling af open/ source (licens a la BSD) general purpose klasser/libaries

Hvis at man vil have en lidt enklere tilgang til hukommelses styringen kan man bruge lidt tid på at undersøge RAII og brugen af f.eks. std::auto_ptr. Se evt også denne ONLamp artikel

Her er en udemærket artikel omkring exception handling

C++ casting operators

(Citat fra Learning DCOM af Thuan L. Thai)

We all know the power or evilness of the C-style cast, which allows us to cast a given type to practically any other type that we want. For example, we can cast a human into an ant. This can be extremely dangerous, because it can create uncontrollable and error-prone software. To migitate casting problems, C++ allows us to spcifically indicate the kind of cast that we want to apply. Check with compiler documentation for the details of the C++ casting operators. In a nutshell, here they are and their short meanings.

  • dynamic_cast
    • Used to convert polymorphic types. Runtime checks will be made to ensure the validity of the cast. If the cast is not safe, a bad_cast exception will be thrown.
  • static_cast
    • Used to convert nonpolymorphic types. No runtime check is involved.
  • const_cast
    • Used to cast away const-ness or volatile-ness of an object.
  • reinterpret_cast
    • Used to cast any pointer or integral type into another pointer or integral type. This is the most flexible and the most dangerous of the C++ casting operators, second only to the traditional C casting operator.

In the old days, we would do the following to cast a double pointer into a void**: (void**)(&pSome)

If we wanted to use the C++ casting operators, we would write the above code as follows:

reinterpret_cast<void**>(&pSome)

The syntax of the other C++ casting operators follows the same pattern as reinterpret_cast.