【问题标题】:Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end?为什么类的构造函数被调用了四次,而析构函数只在程序即将结束时被调用了两次?
【发布时间】:2021-04-02 14:13:15
【问题描述】:

为什么类的构造函数被调用了四次,而析构函数只在程序快结束的时候被调用了两次?

我想构造一个单向循环链表,没问题,但是Bufferclass的析构函数出现了一些问题。

代码如下:

#include <iostream>
#include <string>
#include <memory>
using namespace std;

class Buffer
{
public:
    Buffer(): Next(nullptr)
    {
        int id = ID + 1;
        ID++;
        std::cout << "Thi is the " << id << "th buffer." << endl;
    }
    ~Buffer()
    {
        cout << "The buffer is destructed." << endl;
    }

    shared_ptr<Buffer> Next;
    static int ID;
};

int Buffer::ID = 0;

int main()
{
    int LogBufferNum = 4;
    shared_ptr<Buffer> Head = std::make_shared<Buffer>();
    Head->Next = Head;
    LogBufferNum--;

    while (LogBufferNum > 0)
    {
        std::shared_ptr<Buffer> New = std::make_shared<Buffer>();
        std::shared_ptr<Buffer> Temp(Head);

        New->Next = Head;
        Temp->Next = New;
        Temp = New;

        LogBufferNum--;
    }
    return 0;
}

它打印为:

The is the 1th buffer.
The is the 2th buffer.
The is the 3th buffer.
The buffer is destructed.
The is the 4th buffer.
The buffer is destructed.

有什么解决办法吗? 非常感谢

【问题讨论】:

  • 为了更好地了解正在发生的事情,cout &lt;&lt; "The buffer is destructed." &lt;&lt; endl; 似乎应该改为 cout &lt;&lt; "The " &lt;&lt; id &lt;&lt; "th buffer is destructed." &lt;&lt; endl;

标签: c++ class constructor destructor


【解决方案1】:

当您使用 shared_ptr 创建循环引用时,即 A 包含指向 B 的指针,B 包含指向 A 的指针,这些对象将永远不会被销毁。在这种情况下,您的两个Buffers 相互指向。当你设置这些指针时,试着在纸上计算你在做什么,你会看到循环引用。

【讨论】:

    猜你喜欢
    • 2013-12-11
    • 2022-07-05
    • 2013-01-12
    • 2013-11-24
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多