C++ variable declaration and initialization rules

2019-04-11 19:16发布

问题:

Consider the following ways of declaring and initializing a variable of type C:

C c1;

C c2;
c2 = C();

C c3(C());

C c4 = C();

Are all of these completely equivalent to each other, or can some of these differ depending on the exact definition of C? (assuming it has public default and copy constructors).

回答1:

These mean:

C c1;   // default constructor

C c2;   // default constructor
c2 = C(); // default constructor followed by assignment

C c3(C());   // default constructor possibly followed by copy constructor

C c4 = C();  // default constructor possibly followed by copy constructor

Note the compiler can elide copy constructor calls. Are they equivalent? - well, it depends on what the copy constructor and assignment operator do.