我正在尝试使用智能指针实现双端队列。但是,我注意到在程序结束时,双端队列的节点没有被正确破坏。
这是代码:
#include<iostream>
#include<memory>
class Node
{
int value;
std::shared_ptr<Node> next = nullptr;
std::shared_ptr<Node> prev = nullptr;
public:
Node() = default;
Node(int val): value(val) {}
~Node()
{
std::cout << "Destructor of node: " << value << std::endl;
}
friend class Deque;
};
class Deque
{
using pointer = std::shared_ptr<Node>;
pointer head = nullptr; // pointer to the first element of the queue
pointer tail = nullptr; // pointer to the last element of the queue
public:
Deque() = default;
~Deque(){ std::cout << "Dequeue destructor" << std::endl; }
bool is_empty()
{
if (head == nullptr && tail == nullptr )
return true;
else
return false;
}
void push_back(const pointer& val)
{
if (is_empty())
{
head = val;
tail = val;
}
else
{
val->prev = tail;
tail->next = val;
tail = val;
}
}
};
int main()
{
Deque DEQ;
auto node1 = std::make_shared< Node >(1);
auto node2 = std::make_shared< Node >(2);
auto node3 = std::make_shared< Node >(3);
DEQ.push_back(node1);
DEQ.push_back(node2);
std::cout << "Use count node1 = " << node1.use_count() << std::endl;
std::cout << "Use count node2 = " << node2.use_count() << std::endl;
std::cout << "Use count node3 = " << node3.use_count() << std::endl;
return 0;
}
输出如下:Use count node1 = 3
Use count node2 = 3
Use count node3 = 1
Destructor of node: 3
Dequeue destructor
当我推 node1
和 node2
进入双端队列,它们在程序结束时不会被破坏,而 node3
被正确破坏。我认为问题在于
node1
的引用计数和 node2
等于 3。你知道我可以如何改变我的实现来解决这个问题吗?谢谢。
最佳答案
I assume the problem is that the reference count of node1 and node2 is equal to 3.
你的假设是正确的。共享指针不会破坏指向的对象,直到引用计数降至零。
Do you know how I can change my implementation in order to solve this problem?
所有权图中没有循环。例如,您可以在列表的一个方向使用拥有智能指针,而在另一个方向使用非拥有指针(可能是弱指针)。
关于c++ - shared_ptr 不会在程序结束时破坏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64282322/