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

后端 未结 8 1433
失恋的感觉
失恋的感觉 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
    };
    
    0 讨论(0)
  • 2020-12-03 04:02

    For me its the disabling feature that will be useful, For most of the classes I currently create I disable copying & assignment - it will be nice to have a feature the compiler can recognise to do this, rather than depending on linker errors.

    0 讨论(0)
提交回复
热议问题