Explicit constructor taking multiple arguments

前端 未结 4 1074
面向向阳花
面向向阳花 2021-01-30 03:36

Does making a constructor having multiple arguments explicit have any (useful) effect?

Example:

class A {
    public:
        explicit A( in         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 04:12

    The excellent answers by @StoryTeller and @Sneftel are the main reason. However, IMHO, this makes sense (at least I do it), as part of future proofing later changes to the code. Consider your example:

    class A {
        public:
            explicit A( int b, int c ); 
    };
    

    This code doesn't directly benefit from explicit.

    Some time later, you decide to add a default value for c, so it becomes this:

    class A {
        public:
            A( int b, int c=0 ); 
    };
    

    When doing this, you're focussing on the c parameter - in retrospect, it should have a default value. You're not necessarily focussing on whether A itself should be implicitly constructed. Unfortunately, this change makes explicit relevant again.

    So, in order to convey that a ctor is explicit, it might pay to do so when first writing the method.

提交回复
热议问题