问题描述
我正在尝试使用智能指针实现Deque。但是,我注意到在程序结束时,双端队列的节点没有被正确地破坏。
这是代码:
#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。您知道如何更改我的实现以解决此问题吗?谢谢。
解决方法
我认为问题在于节点1和节点2的引用计数等于3。
您的假设是正确的。共享指针在引用计数降至零之前不会破坏指向的对象。
您知道我可以如何更改实施方式以解决此问题?
所有权图中没有循环。例如,您可以在列表的一个方向上使用拥有的智能指针,而在另一个方向上使用非拥有的指针(也许是弱指针)。