0

我对编译器的工作方式有点困惑我用 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,为什么会这样?

4

0 回答 0