为对象分配值时为什么调用构造函数和析构函数

Kam*_*Pop 2 c++ constructor destructor assignment-operator

我有以下代码:

#include <iostream>

using namespace std;

class A{
    int x;
public:
    A(int x =1) : x(x) {cout << "A() ";}
    A(const A& a) {x =a.x; cout << "A(const A&) ";}
    A& operator=(const A& a){cout << "op= "; x=a.x; return *this;}
    ~A(){cout << "~A()";}
    int getX() {return x;}
    void setX(int x){this->x = x;}
};


A g(A a){
    //a = 2;
    cout << "g() ";
    a.setX(3);
    return a;
}

int main()
{
    A a;
    a = 2;

}
Run Code Online (Sandbox Code Playgroud)

我期望有以下输出:A() op= ~A(),但输出是A() A() op= ~A() ~A()。当我将值赋给2对象时,似乎调用了构造函数和析构函数a。为什么叫那两个?编译器是否有效地创建了一个新A对象,该对象具有x = 2,然后使用赋值运算符将值赋给a

小智 6

这是因为您没有为类声明将int作为参数的赋值运算符。因为不存在这样的运算符,所以编译器需要使用变通方法:它使用构造函数A(int)创建一个临时对象。您可以通过使构造函数显式来避免此行为:

explicit A(int x_ = 1) : x(x_) { }
Run Code Online (Sandbox Code Playgroud)

构造临时文件后,使用提供给A的副本构造函数将其复制到“ a”。此后,临时文件立即销毁并调用其析构函数。

这种方法效率低下。为了使它更好,您应该为A定义一个赋值运算符,并以一个int作为参数:

A& operator= (int x_) {
    x = x_;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)