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

#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;
}

输出如下所示
 defaul constructir called  23

 ----------

 COPY constructir called    24

 ----------

 COPY constructir called    24

 = operator  called 25

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

当我没有制作新对象但正在使用旧对象时,为什么还要调用复制构造函数呢?

是因为它们之间存在临时对象,如果可以,我可以在这里停止它们吗....

最佳答案

man& operator =(man x);

您的参数使用其参数by-value,当发生这种情况时,它将调用copy-constructor。这就是造成额外不必要调用的原因。通过引用传递参数将避免重复,但是您将无法传递临时变量(通常称为rvalues):
struct man
{
    man& operator =(man& x) { return *this; };
};

int main()
{
    man a, b;

    a = b;     // works
    a = man(); // error: no viable overloaded '=',
               // expected an l-value for 1st argument
}

通过传递对const的引用,将允许左值和右值的复制构造:
man& operator =(man const& x);
//                  ^^^^^

10-07 13:37