What's the point in defaulting functions in C++11?

后端 未结 8 1460
失恋的感觉
失恋的感觉 2020-12-03 03:41

C++11 adds the ability for telling the compiler to create a default implementation of any of the special member functions. While I can see the value of deleting a function,

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 03:48

    Defaulting is more useful for copy-constructors if you have a class with lots of attributes. For example, if you have this class:

    class MyClass {
    private:
       int offset;
       std::string name;
       std::vector relatives;
       float weight;
       MyClass* spouse;
       Vehicle* car;
       double houseArea;
       Date birth;
       Person* parents[2];
    
    public:
       /* Default constructor will be defined here */
    };
    

    instead of defining the copy-constructor this way:

    MyClass(const MyClass& that) :
       offset(that.offset),
       name(that.name),
       relatives(that.relatives),
       weight(that.weight),
       spouse(that.spouse),
       car(that.car),
       houseArea(that.houseArea),
       birth(that.birth),
       parents(that.parents)
    {}
    

    you would define this way:

    MyClass(const MyClass&) = default;
    

提交回复
热议问题