Purpose of Explicit Default Constructors

后端 未结 2 1938
无人共我
无人共我 2020-12-04 22:04

I recently noticed a class in C++0x that calls for an explicit default constructor. However, I\'m failing to come up with a scenario in which a default constructor can be c

2条回答
  •  感情败类
    2020-12-04 22:33

    This declares an explicit default constructor:

    struct A {
      explicit A(int a1 = 0);
    };
    
    A a = 0; /* not allowed */
    A b; /* allowed */
    A c(0); /* allowed */
    

    In case there is no parameter, like in the following example, the explicit is redundant.

    struct A {
      /* explicit is redundant. */
      explicit A();
    };
    

    In some C++0x draft (I believe it was n3035), it made a difference in the following way:

    A a = {}; /* error! */
    A b{}; /* alright */
    
    void function(A a);
    void f() { function({}); /* error! */ }
    

    But in the FCD, they changed this (though, I suspect that they didn't have this particular reason in mind) in that all three cases value-initialize the respective object. Value-initialization doesn't do the overload-resolution dance and thus won't fail on explicit constructors.

提交回复
热议问题