Copy constructor curly braces initialization

爷,独闯天下 提交于 2019-11-28 03:47:55

问题


"we can initializate objects of a class for which we have not define any constructor using:

  • memberwise initialization.
  • copy initialization.
  • default initialization.

For example:

    struct Work {
      string author;
      string name;
      int year;
    };

    Work s9 { "Bethoven",
              "Symphony No. 9 in D minor, Op. 125; Choral",
              1824
            };                    // memberwise initialization

    Work currently_playing {s9};  // copy initialization
    Work none {};                 // default initialization

The C++ Programming Language 4th Ed. Chapter 17.3.1

For example:

   struct Data
     {
        int mMember1;
        float mMember2;
        char mMember3;
     };

     int main()
     {
         Data aData_1{1,0.3,33};
         Data aData_2{aData_1};

         return EXIT_SUCCESS;
     }

This must work, althought I get a compiler error as much with GCC as with Clang. The error is "cannot convert Data to int" in both compilers. However, implementing the copy constructor this error disappear or without implenting it but using the round braces syntax. The problem is a little stupid and changing the curly for the round braces the problem get solved. But why the rules of TC++PL are not followed?, is a compilator issue or I'm misunderstanding something?. Thanks in advance.


回答1:


I think the behaviour conforms with 8.5.4 (List initialization), sentence 3:

List-initialization of an object or reference of type T is defined as follows:

— If T is an aggregate, aggregate initialization is performed (8.5.1).

[...]

— Otherwise, if the initializer list has a single element of type E [...] the object or reference is initialized from that element;

You were expecting the second item in my abbreviated quote to apply, but the first item takes precedence: Since Data is indeed an aggregate, the one-element-list clause is never considered.


Your quote from the book appears to be a known error. The language is allegedly going to be fixed to match the book in C++14.



来源:https://stackoverflow.com/questions/19347004/copy-constructor-curly-braces-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!