我对编译器的工作原理有点困惑 我使用g ++ -fno-elide-constructors test.cpp
编译了prog#include <iostream>
using namespace std;
class c
{
int i;
public:
~c(){cout<<"Destroying"<<endl;}
c(){cout<<"Constructing"<<endl;}
c(const c &a){cout<<"Copy Constructing"<<endl; this->i = a.i;}
int get_i(){cout<<"Getting "<<i<<endl;return i;}
void set_i(int i){cout<<"Setting"<<endl; this->i=i;}
c operator=(c op2) {cout<<"Assignemnt operator"<<endl; i = op2.i; return *this; }
};
c f(){
c obj;
obj.set_i(1);
return obj;
}
void f1() {
c obj1 = f();
c obj2 = obj1;
obj2.get_i();
}
void f2() {
c obj1 = f();
c obj2;
obj2 = obj1;
obj2.get_i();
}
int main() {
cout<<"++++++++++++++++++++++++++++++++"<<endl;
f1();
cout<<"++++++++++++++++++++++++++++++++"<<endl;
f2();
cout<<"++++++++++++++++++++++++++++++++"<<endl;
return 0;
}
output:
++++++++++++++++++++++++++++++++
Constructing
Setting
Copy Constructing
Destroying
Copy Constructing
Destroying
Copy Constructing
Getting 1
Destroying
Destroying
++++++++++++++++++++++++++++++++
Constructing
Setting
Copy Constructing
Destroying
Copy Constructing
Destroying
Constructing
Copy Constructing
Assignemnt operator
Copy Constructing
Destroying
Destroying
Getting 1
Destroying
Destroying
++++++++++++++++++++++++++++++++
f1的输出没问题,但是在f2中,我在赋值运算符后也得到了复制const,为什么会这样?