#include <iostream>
#include <exception>
#include <assert.h>
using namespace std;
template<typename T>
class Stack
{
public:
Stack():v_(new T[10]),vused_(0),vsize_(10)
{}
Stack(const Stack& other):
v_(newCopy(other.v_,other.vsize_,other.vsize_)),
vused_(other.vused_),
vsize_(other.vsize_)
{}
Stack& operator=(const Stack& other)
{
if (this != &other)
{
v_new = newCopy(other.v_,other.vsize_,other.vsize_);//may throw,delete after new success,pay attention;
delete [] v_;
v_ = v_new;
vused_ = other.vused_;
vsize_ = other.vsize_;
}
return *this;
}
~Stack()
{
delete [] v_;
}
bool Empty()
{
return 0 == vused_;
}
int Count()const
{
return vused_;
}
void Push(const T& t)
{
if(vused_ == vsize_)
{
size_t vsize_new = 2*vsize_ + 1;
T* v_new = newCopy(v_,vsize_,vsize_new);
delete [] v_;
v_ = v_new;
vsize_ = vsize_new;
}
v_[vused_] = t;//may throw and make not strong exception-safe;
vused_++;
}
void Pop()
{
if (vused_ == 0)
{
throw "pop from empty stack";
}
else
{
--vused_;
}
}
T& Top()
{
if (vused_ == 0)
{
throw "empty stack";
}
return v_[vused_-1];
}
private:
T* newCopy(const T* src,size_t srcsize,size_t destsize)
{
assert(destsize >= srcsize);
T* dest = new T[destsize];
try
{
copy(src,src+srcsize,dest);
}
catch(...)
{
delete [] dest;
throw;
}
return dest;
}
private:
T* v_;
size_t vsize_;
size_t vused_;
};
1、注意该栈实现的接口与标准库中实现的一致性,将pop的功能分离成pop和top
2、该类的异常安全性依赖于容器中实例元素的拷贝复制函数的异常安全性