C++ variable declaration and initialization rules

ⅰ亾dé卋堺 提交于 2019-12-06 06:49:56

问题


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.



来源:https://stackoverflow.com/questions/3398285/c-variable-declaration-and-initialization-rules

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