c++ - 为什么析构函数在 C++ 中运行两次?

标签 c++ constructor destructor

在做我的编程作业时,我似乎被基本的 C++ 概念绊倒了。我在我的程序中发现了这个错误,它是由我的析构函数运行的次数超出我的预期造成的。这是一个代码示例,展示了我做错了什么,直到最基本的部分。

#include <iostream>
using namespace std;

class A
{
public:
    A(int num)
    {
        number = num;
        cout << "A constructed with number " << number << ".\n";
    }
    ~A()
    {
        cout << "A destructed with number " << number << ".\n";
    }
private:
    int number;
};

class B
{
public:
    B(A pa)
        : a(pa)
    {
        cout << "B constructor run.\n";
    }
    ~B()
    {
        cout << "B destructor run.\n";
    }
private:
    A a;
};


int main()
{
    A foo(7);
    {
        B bar(foo);
    }
    //Pause the program.
    system("pause");
}

我希望发生的是 A foo(7); 在堆栈上为名为 fooA 对象分配空间并调用构造函数,传递 7。它将 7 分配给 number 并打印指示构造函数运行的输出。现在 B bar(foo); 在堆栈上为名为 barB 对象分配空间并调用构造函数,传递 foo 按值,它只是 int 的容器。构造函数将传递给它的 A 参数分配给它自己的私有(private)数据成员 a,并将输出打印到屏幕。

现在,当 bar 在右花括号处超出范围时,我希望调用 bar 的析构函数,它将输出打印到屏幕,然后调用其数据成员的析构函数,即 A a。该析构函数将输出打印到屏幕,并丢弃它包含的 int number

我期望的输出应该是:

A constructed with number 7.
B constructor run.
B destructor run.
A destructed with number 7.
//Destructors should be called in the reverse order of their construction right?

实际输出:

A constructed with number 7.
B constructor run.
A destructed with number 7. //This is unexpected.
B destructor run.
A destructed with number 7.

是什么造成了额外的破坏?

最佳答案

B 构造函数按值获取 A 对象,这意味着 foo 被复制到参数 pa 然后将其复制到成员 a。编译器已经能够省略一个拷贝(构造函数的参数),但无法省略另一个拷贝,并且您有第二个被销毁的 A 对象。

关于c++ - 为什么析构函数在 C++ 中运行两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10875381/

相关文章:

c++ - 创建简单链表时无法访问内存

c# - 如何在 C# 中处理托管和非托管对象?

c++ - "Why switch statement cannot be applied on strings?"的答案是否仍然正确,即使使用 C++11/14?

c++ - std::string 得到一个完全出乎意料的值

c++ - gcc (mingw) 中的静态链接

c++ - 数据库连接可以重用吗?

c++ - 处理失败的构造函数

c++ - 在构造函数中调用虚函数

c++ - 基类和派生类的析构函数c++

c++ - 在 C++ 中删除指针数组时析构函数崩溃