First thing's first, you have some major issues with your pop
method.
- You correctly replace
head
with the next node in the chain but you neverdelete
the previous node, leading to a memory leak. - The method returns before you set the head to null on the empty condition.
- Less sever but you're comparing to
true
andfalse
, which is a redundancy very commonly found in beginner code.
This should be rectified like so:
if(!this->isEmpty()) // !true = false, !false = true
{
T data = std::move(temp->head->data); // Move the data out of the node
Node *temp = this->head_;
this->head_ = this->head_->next_;
this->size_ --;
delete temp; // Delete the node so it doesn't leak
if(this->isEmpty()) // == true comparison was redundant
this->head_ = nullptr; // Use nullptr, not NULL
return data;
}
else
{
throw std::out_of_range("The Stack Is Empty!");
}
More about std::move
More about std::move
.
Advice 1: Const Correctness
This is probably less important than other answers but you should try to make your code const-correct.
isEmpty
and getSize
should be marked const
.
This means you'll be able to use them from a const reference to an instance of TStack
.
Advice 2: nullptr
If you're using a modern (C++11 onwards) compiler, user nullptr
instead of the archaic NULL
.
Extra suggestion:
Add a const T& peek() const
method so you can examine the top of the stack without removing it. This isn't completely necessary but if I were one of the people using your stack object I'd expect the peek operation to be available.