Refactoring with C++ 11

前端 未结 11 2367
夕颜
夕颜 2020-11-28 18:17

Given the new toolset provided by c++ lots of programmers, aiming at code simplification, expressiveness, efficiency, skim through their old code and make tweaks (some point

11条回答
  •  無奈伤痛
    2020-11-28 18:53

    I would add delegating constructors and in-class member initializers to the list.

    Simplification By Using Delegating Constructors and In-Class Initialization

    With C++03:

    class A
    {
      public:
    
        // The default constructor as well as the copy constructor need to 
        // initialize some of the members almost the same and call init() to
        // finish construction.
        A(double data) : id_(0), name_(), data_(data) {init();}
        A(A const& copy) : id_(0), name_(), data_(copy.data_) {init();}
    
        void init()
        {
           id_ = getNextID();
           name_ = getDefaultName();
        }
    
        int id_;
        string name_;
        double data_;
    };
    

    With C++11:

    class A
    {
      public:
    
        // With delegating constructor, the copy constructor can
        // reuse this constructor and avoid repetitive code.
        // In-line initialization takes care of initializing the members. 
        A(double data) : data_(data) {}
    
        A(A const& copy) : A(copy.data_) {}
    
        int id_ = getNextID();
        string name_ = getDefaultName();
        double data_;
    };
    

提交回复
热议问题