Please comment on the same. How can it be improved?
Specific improvements I am looking for:
- Memory leaks
- C++ style
- Making code run faster
- RAII
#include<iostream>
#include<algorithm>
template <typename T>
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<T>& push(const T&);
Stack<T>& pop();
};
template<typename T>
void Stack<T>::expandArray() {
T* array_temp = new T[length_ << 1];
std::copy(array_, array_ + length_, array_temp);
std::swap(array_, array_temp);
delete[] array_temp;
last_ = array_ + length_ - 1;
length_ <<= 1;
}
template<typename T>
Stack<T>& Stack<T>::push(const T& data) {
if (last_ == (array_ + length_ - 1)) {
expandArray();
}
last_[0] = data;
last_++;
std::cout << "[" << data << "] pushed." << std::endl;
return *this;
}
template<typename T>
Stack<T>& Stack<T>::pop() {
if(array_ != last_) {
last_--;
std::cout << "[" << last_[0] << "] popped." << std::endl;
} else {
std::cout << "Nothing to pop." << std::endl;
}
return *this;
}
int main() {
Stack<std::string> s;
s.push(std::string("a"))
.push(std::string("b"))
.push(std::string("c"))
.push(std::string("d"));
s.pop().pop().pop().pop().pop();
}