将C ++链接的堆栈转换为智能指针

问题描述

我对将以下代码转换为智能指针有疑问,尤其是在共享指针方面。 Node.cpp是类模板Node<T>的实现文件,其构造函数定义如下。

Node.cpp

...
template <typename T>
Node<T>::Node(const T& anItem,std::shared_ptr<Node<T>> nextNodePtr)
    : item(anItem),next(nextNodePtr) { }

...

LinkedStack.cpp

...
template <typename T>
bool LinkedStack<T>::push(const T& newItem) {

   topPtr = new Node<T>(newItem,topPtr);

   return true;
}
...

LinkedStack.cpp(就共享指针而言,我的尝试)

...
template <typename T>
bool LinkedStack<T>::push(const T& newItem) {

   std::shared_ptr<Node<T>> topPtr
       = std::make_shared<Node<T>>(Node<T>(newItem,topPtr));
   return true;
}
...

这是将LinkedStack.cpp转换为使用共享指针的形式的正确方法吗?

解决方法

std::shared_ptr<Node<T>> topPtr声明了一个全新的局部范围变量,并隐藏了我认为是topPtr成员变量的LinkedStack。结果几乎立即破坏了本地topPtrLinkedStack::topPtr

中没有任何内容

您需要执行更多类似转换前的版本:

topPtr = std::make_shared<Node<T>>(Node<T>(newItem,topPtr));