Effective C++ Ed. 3rd: Item 27. Minimise casting

Instead of "old" C style casts:



(T) expression             // cast expression to be of type T 
T(expression)           // cast expression to be of type T



Prefer C++ style-casts:

  1. const_cast: To convert const datatype to non-const datatype.
  2. reinterpret_cast: For low-level cast.
  3. static_cast: to force implicit casts.
  4. dynamic_cast: to perform safe-downcasting. For example:
    Derived *pd = new Derived();
    if ( Base *pb = dynamic_cast <   Base*  > pd )
        doSomething(); // returns true;
    if ( SuperDerived *pd2 = dynamic_cast <SuperDerived*> pd )
        doSomething(); // returns false; 
Following code compiles but doesn't run as you might expect:
class Window
{                                               // base class
public:
  virtual void onResize() { ... }   // base onResize impl  
...
};
class SpecialWindow: public Window {          // derived class
    virtual void onResize(){        // derived onResize impl;
    static_cast<Window>(*this).onResize();    // cast *this to Window,
                                              // then call its onResize;
                                              // this doesn't work!
    ...                                       // do SpecialWindow-
  }
                                           // specific stuff
  ...
};

Simply use
Window::onResize();
  instead of the line 9 above.

Note: Minimize use of casts, specially dynamic_cast.
prev | next

No comments:

Post a Comment