C ++ core principles C.51: using a delegate constructor to achieve common action of all constructors

. 51 s: Represent the Use The Delegating Constructors Common to All Actions for Constructors of A class
. 51 s: delegate using a constructor implemented in common operation of all constructors

 

Delegate constructor is a new feature introduced in C ++ 11, please refer to the specific author of the following article:

https://mp.weixin.qq.com/s/sHyLCI1tkLWvxfBKUiKwMg

 

Reason (reason)

To avoid repetition and accidental differences.

Avoid duplication and unexpected differences.

 

Example, bad (negative sample)

 

class Date {   // BAD: repetitive
    int d;
    Month m;
    int y;
public:
    Date(int dd, Month mm, year yy)
        :d{dd}, m{mm}, y{yy}
        { if (!valid(d, m, y)) throw Bad_date{}; }

    Date(int dd, Month mm)
        :d{dd}, m{mm} y{current_year()}
        { if (!valid(d, m, y)) throw Bad_date{}; }
    // ...
};

 

The common action gets tedious to write and may accidentally not be common.

Common action to write tedious, occasionally become common.

 

 

Example (Example)

 

class Date2 {
    int d;
    Month m;
    int y;
public:
    Date2(int dd, Month mm, year yy)
        :d{dd}, m{mm}, y{yy}
        { if (!valid(d, m, y)) throw Bad_date{}; }

    Date2(int dd, Month mm)
        :Date2{dd, mm, current_year()} {}
    // ...
};

 

See also: If the "repeated action" is a simple initialization, consider an in-class member initializer.

Reference: If the "repeat action" simply initialization, class member initializer contemplated.

 

Enforcement (Suggestions)

(Moderate) Look for similar constructor bodies.

(Average) looking similar body of the constructor.

 

Description link

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c51-use-delegating-constructors-to-represent-common-actions-for-all-constructors-of-a-class

 


 

I think this article helpful? Welcome thumbs up and share it with more people.

Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []

Published 408 original articles · won praise 653 · views 290 000 +

Guess you like

Origin blog.csdn.net/craftsman1970/article/details/104596994