【问题标题】:Why is the constructor and the destructor called when assigning a value to an object给对象赋值时为什么要调用构造函数和析构函数
【发布时间】:2019-11-16 07:10:06
【问题描述】:

我有以下代码:

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

}

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

【问题讨论】:

  • 是的。 (您没有接受int 的赋值运算符)。
  • 因为类没有赋值运算符,所以创建了类的临时实例,然后复制分配给现有对象,然后销毁。
  • 是的,添加了另一个 int 赋值运算符 A& operator=(const int n){cout
  • 顺便说一句:您的编码风格无处不在。您将函数体的花括号放在三个不同的位置。 ){) {)\n{。选一个。请问?
  • 哦,我通常使用一种样式,但是这段代码的一半是已经编写好的示例,另一半是我的代码。

标签: c++ constructor destructor assignment-operator


【解决方案1】:

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

explicit A(int x_ = 1) : x(x_) { }

在构造临时对象后,它会使用为 A 提供的复制构造函数复制到“a”。紧接着,临时对象被销毁并调用其析构函数。

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

A& operator= (int x_) {
    x = x_;
    return *this;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 2011-05-21
    • 2021-04-01
    • 1970-01-01
    • 2020-08-24
    • 2016-06-25
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多