复制construtor称为额外

MAG*_*MAG 3 c++ constructor copy-constructor

我有一个显示奇怪行为的程序

#include <cstdlib>
#include <iostream>

using namespace std;
class man{
           int i ;
      public:
           man(){
             i=23;
             cout << "\n defaul constructir called\t"<< i<<"\n";
           }
           man (const man & X) {
               i = 24;
           cout << "\n COPY constructir called\t"<< i<<"\n";
           }       
           man &  operator = (man x ) {
               i = 25;
               cout << "\n = operator  called\t"<< i<<"\n"; 
               return *this;
           }      
      };

int main(int argc, char *argv[])
{

     man x;
     cout <<"\n ----------\n";
     man y = x;
     cout <<"\n ----------\n";
     x=y;


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出显示在

 defaul constructir called  23

 ----------

 COPY constructir called    24

 ----------

 COPY constructir called    24

 = operator  called 25
Run Code Online (Sandbox Code Playgroud)

对于x = y的第三次调用,此输出很奇怪;

当我没有制作新对象但正在处理旧对象时,为什么会有一个额外的复制construtor打印.

是否因为两者之间的临时物体,如果是,我可以在这里阻止它们....

Oli*_*rth 12

因为赋值运算符按值获取其参数.您可以通过const引用来取而代之.