Cpp

From HoerupWiki
Revision as of 11:47, 20 January 2007 by 192.168.10.10 (talk) (C++ casting operators: fixed typo)
Jump to: navigation, search

Der er mange gode artikler om c++ på informit.com. Dr. Dobb's Journal kigger også på mange programmerins-relaterede emner så som C++ views

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 specifically 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.