为什么class的构造函数调用了四次,而析构函数只在程序快结束的时候调用了两次?
Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end?
为什么class的构造函数调用了四次,而析构函数只在程序快结束的时候调用了两次?
我想构造一个单向循环链表,没问题,但是我在Buffer
class.
的析构函数上遇到了一些问题
代码如下:
#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.
有什么解决办法吗? 非常感谢
当您使用 shared_ptr
创建循环引用时,即 A 包含指向 B 的指针,B 包含指向 A 的指针,这些对象将永远不会被销毁。在这种情况下,您的两个 Buffers
指向彼此。当你设置这些指针时,试着在纸上计算出你在做什么,你会看到循环引用。
为什么class的构造函数调用了四次,而析构函数只在程序快结束的时候调用了两次?
我想构造一个单向循环链表,没问题,但是我在Buffer
class.
代码如下:
#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.
有什么解决办法吗? 非常感谢
当您使用 shared_ptr
创建循环引用时,即 A 包含指向 B 的指针,B 包含指向 A 的指针,这些对象将永远不会被销毁。在这种情况下,您的两个 Buffers
指向彼此。当你设置这些指针时,试着在纸上计算出你在做什么,你会看到循环引用。