patterncppModerate
Stack implementation using arrays
Viewed 0 times
implementationarraysusingstack
Problem
Please comment on the same. How can it be improved?
Specific improvements I am looking for:
Specific improvements I am looking for:
- Memory leaks
- C++ style
- Making code run faster
- RAII
#include
#include
template
class Stack {
private:
T* array_;
int length_;
T* last_;
void expandArray();
public:
Stack(int length = 8) :
array_(new T[length]),
length_(length),
last_(array_)
{}
Stack& push(const T&);
Stack& pop();
};
template
void Stack::expandArray() {
T* array_temp = new T[length_
Stack& Stack::push(const T& data) {
if (last_ == (array_ + length_ - 1)) {
expandArray();
}
last_[0] = data;
last_++;
std::cout
Stack& Stack::pop() {
if(array_ != last_) {
last_--;
std::cout s;
s.push(std::string("a"))
.push(std::string("b"))
.push(std::string("c"))
.push(std::string("d"));
s.pop().pop().pop().pop().pop();
}Solution
First of all, I would specify that your stack is using a "dynamically allocated array", as opposed to just an array, as I at first expected a C array when looking at the title. That varies from person to person, though.
On to more important things:
On to more important things:
- I would not print anything in the stack functions. If someone wants information on what they're pushing and popping, let them do it themselves.
- You seem to be missing a peek function.
- Either throw an exception or add an assert to pop for the
array_ == last_case.
length_should actually be calledcapacity_.
expandArraymay leak memory if the copy throws. I would use anstd::vectorinternally for this stuff.
- You don't check that
length > 0in the constructor.
- I would not allocate so anything by default.
- You lack all three of a copy constructor, assignment operator, and destructor, so you'll definitely leak memory. You should also have a move constructor and a move assignment operator, but those aren't as critical.
- You provide no way to check whether the stack is empty.
Context
StackExchange Code Review Q#15640, answer score: 11
Revisions (0)
No revisions yet.