简体   繁体   中英

Converting C++ linked stack into smart pointers

I have a question on converting the following code into smart pointers, in particular in terms of shared pointers. Node.cpp is an implementation file of the class template Node<T> , wherein its constructor is defined as below.

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 (in terms of shared pointers, my attempt)

...
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;
}
...

Is this a correct way to transform LinkedStack.cpp into the form that uses shared pointers?

std::shared_ptr<Node<T>> topPtr declared a brand new, locally scoped variable and hid the topPtr that I assume is a LinkedStack member variable. The result is nearly instant destruction of the local topPtr . and nothing ever placed in the LinkedStack::topPtr

You need to do something more like the pre-transformation version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM