Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

c++ - Copy constructor curly braces initialization

"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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...