【发布时间】: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 << "The buffer is destructed." << endl;似乎应该改为cout << "The " << id << "th buffer is destructed." << endl;。
标签: c++ class constructor destructor