Defaulted constructor vs implicit constructor

后端 未结 2 1146
走了就别回头了
走了就别回头了 2021-01-19 23:59

It\'s possible that someone has already asked about this but googling for \"default\", \"defaulted\", \"explicit\" and so on doesn\'t give good results. But anyway.

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 00:09

    The purpose of = default is to make the implicit definition explicit. Any differences between an implicitly defined version and the explicitly defaulted version are limited to some additional possibilities appearing due to the presence of an explicit declaration.

    1. The implicitly declared/defined constructor is always public, whereas the access control of the explicitly defined defaulted constructor is under your own control.

    2. Defining a defaulted default constructor enables you annotating it with attributes. For example:

      $ cat a.cpp 
      class A
      {
      public:
          [[deprecated]] A() = default;
      };
      
      int main()
      {
          A a;
      }
      
      $ g++ -std=c++14 a.cpp
      a.cpp: In function ‘int main()’:
      a.cpp:9:7: warning: ‘constexpr A::A()’ is deprecated [-Wdeprecated-declarations]
           A a;
             ^
      a.cpp:4:20: note: declared here
           [[deprecated]] A() = default;
                          ^
      

提交回复
热议问题