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

后端 未结 8 1452
失恋的感觉
失恋的感觉 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 04:00

    Those examples from Stroustrup's website might help you understand the point:

    defaulted and deleted functions -- control of defaults

    The common idiom of "prohibiting copying" can now be expressed directly:

    class X {
      // ...
    
      X& operator=(const X&) = delete;    // Disallow copying
      X(const X&) = delete;
    };
    

    Conversely, we can also say explicitly that we want to default copy behavior:

    class Y {
      // ...
      Y& operator=(const Y&) = default;   // default copy semantics
      Y(const Y&) = default;
    
    };
    

    Being explicit about the default is obviously redundant, but comments to that effect and (worse) a user explicitly defining copy operations meant to give the default behavior are not uncommon. Leaving it to the compiler to implement the default behavior is simpler, less error-prone, and often leads to better object code. The "default" mechanism can be used for any function that has a default. The "delete" mechanism can be used for any function. For example, we can eliminate an undesired conversion like this:

    struct Z {
      // ...
    
      Z(long long);     // can initialize with an long long
      Z(long) = delete; // but not anything less
    };
    

提交回复
热议问题