为什么在分配之前有副本?

Hai*_*ang 6 c++

我正在做以下测试:

#include <iostream>
#include <vector>

using namespace std;
class A
{
private:
   int i;
public:
   A():i(1){cout<<"A constr"<<endl;}
   A(const A & a):i(a.i){cout<<"A copy"<<endl;}
   virtual ~A(){cout<<"destruct A"<<endl;}
   void operator=(const A a){cout<<"A assign"<<endl;}
};


int main()
{
   A o1; 
   A o2; 
   o2=o1;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

A constr
A constr
A copy
A assign
destruct A
destruct A
destruct A
Run Code Online (Sandbox Code Playgroud)

似乎"o2 = o1"先做了一个副本,然后是一个作业,我想知道背后的故事是什么.谢谢!

CB *_*ley 15

因为您将值传递给赋值运算符:

void operator=(const A a)
Run Code Online (Sandbox Code Playgroud)

您可能希望通过引用传递,并且还应该返回对assign-to对象的引用:

A& operator=(const A& a) { std::cout << "A assign" << std::endl; return *this; }
Run Code Online (Sandbox Code Playgroud)