need help with smart pointers

i need help changing the following code from raw pointers to shared pointers.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98


#include <new>
#include <string>

#include "PrecondViolatedExcep.h"

template <typename ItemType>
LinkedStack<ItemType>::LinkedStack(const LinkedStack<ItemType>& aStack) {

if (aStack.topPtr == nullptr) {
topPtr = nullptr;
}
else {
Node<ItemType>* origStackPtr(aStack.topPtr);

try {
topPtr = new Node<ItemType>(origStackPtr->getItem() );

Node<ItemType>* newChainPtr(topPtr);

origStackPtr = origStackPtr->getNext();

while (origStackPtr != nullptr) {
newChainPtr->setNext(new Node<ItemType>(origStackPtr->getItem()) );

newChainPtr = newChainPtr->getNext();
origStackPtr = origStackPtr->getNext();
}
}
catch(const std::bad_alloc&) {
while (!isEmpty() ) {
pop();
}
throw;
}
}
}

template <typename ItemType>
LinkedStack<ItemType>::~LinkedStack() {

while (!isEmpty() ) {
pop();
}
}

template <typename ItemType>
bool LinkedStack<ItemType>::isEmpty() const {

return topPtr == nullptr;
}

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

bool canPush(true);

try {
topPtr = new Node<ItemType>(newItem, topPtr);
}
catch(const std::bad_alloc&) {
canPush = false;
}

return canPush;
}

template <typename ItemType>
bool LinkedStack<ItemType>::pop() {

bool canPop(!isEmpty() );

if (canPop) {
Node<ItemType>* nodeToDeletePtr(topPtr);

topPtr = topPtr->getNext();

nodeToDeletePtr->setNext(nullptr);
delete nodeToDeletePtr;
}

return canPop;
}

template <typename ItemType>
ItemType LinkedStack<ItemType>::peek() const {
// throw(PrecondViolatedExcep) {

if (isEmpty() ) {
std::string message("LinkedStack::peek() ");
message += "called on an empty stack.";

throw PrecondViolatedExcep(message);
}

return topPtr->getItem();
}
from raw pointers to shared pointers
what is the motivation behind choosing std::shared_ptr over std::unique_ptr?
re std::unique_ptr, here's a link for the copy ctor in a similar, though not exactly same, context:
http://stackoverflow.com/questions/8316062/copy-constructor-with-smart-pointer
in above suggest using std::make_unique instead of the new operator
also
LinkedStack<ItemType>
suggests the container element type is ::value but the following method's implementation
LinkedStack<ItemType>::push(const ItemType& newItem)
seems to suggest pointers are being pushed onto the stack? can you share the full declaration of the datatype for clarification?
Last edited on
Topic archived. No new replies allowed.