c++ - 堆栈上的构造函数/析构函数调用顺序

标签 c++ constructor destructor assignment-operator

我有以下简单代码:

class A
{
    int a;
public:
    A(int a) : a(a) { cout << "Constructor a=" << a << endl; }
    ~A()            { cout << "Destructor  a=" << a << endl; }
    void print()    { cout << "Print       a=" << a << endl; }
};

void f()
{
    A a(1);
    a.print();
    a = A(2);
    a.print();
}

int main()
{
    f();
    return 0;
}

输出是:

Constructor a=1
Print       a=1
Constructor a=2
Destructor  a=2
Print       a=2
Destructor  a=2

我发现 a=2 有两个析构函数调用,a=1 没有一个析构函数调用,而每种情况都有一个构造函数调用。那么在这种情况下如何调用构造函数和析构函数呢?

最佳答案

a = A(2);

将使用默认的 operator=a 赋新值,将其 a::a 成员值设置为 2。

void f()
{
    A a(1);//a created with int constructor a.a == 1
    a.print();// print with a.a == 1
    a = A(2);//Another A created with int constructor setting a.a == 2 and immediately assigning that object to a
    //object created with A(2) deleted printing 2 it was created with
    a.print();//a.a==2 after assign
}//a deleted printing 2 it was assigned with

您可能应该阅读 Rule of three以便更好地了解正在发生的事情。

关于c++ - 堆栈上的构造函数/析构函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129917/

相关文章:

c++ - 插入到特里

haskell - Haskell 中的矩阵构造函数和方法

c++ - 动态分配对象数组

c++ - 线程多次调用析构函数

c++ - 将析构函数作为函数实现?

c++ - 使用来自 USB token 的证书和 key 进行数字签名

c++ - 使用 bazel 构建简单库时包含路径问题

c++ - 从其迭代器返回 std::list 元素的引用

java - 为什么我收到错误 "the Method Is Undefined for the type"?

constructor - 为什么 Pytorch 中未初始化的张量有初始值?