#include <new>
template<class T1, class T2>
void construct(T1* p,const T2& val)
{
new (p) T1(val);
}
template <class T>
void destroy(T* p)
{
p->~T();
}
template <class FwdIter>
void destroy(FwdIter first,FwdIter last)
{
while (first != last)
{
destroy(&*first);
++first;
}
}
template <class T>
void swap(T& a,T& b)
{
T temp(a); a=b;b=temp;
}
template<class T>
class StackImpl
{
protected:
StackImpl(size_t size):
v_(static_cast<T*>
(size == 0 ? 0 :operator new (sizeof(T)*size))),
vused_(0),
vsize_(size)
{}
~StackImpl()
{
destroy(v_,v_ + vused_);
operator delete (v_);
}
void Swap(StackImpl& other) throw()
{
swap(v_,other.v_);
swap(vsize_,other.vsize_);
swap(vused_,other.vused_);
}
T* v_;
size_t vsize_;
size_t vused_;
private:
StackImpl(const StackImpl& other);
StackImpl& operator=(const StackImpl& other);
};
template<class T>
class Stack:private StackImpl<T>
{
public:
Stack(size_t size=0):StackImpl<T>(size)
{}
Stack(const Stack& other):StackImp<T>(other.vused_)
{
while(vused_ < other.vused_)
{
construct(v_+vused_,other.v_[vused_]);
++vused_;
}
}
Stack& operator=(const Stack& other)
{
Stack temp(other);
Swap(temp);
return *this;
}
~Stack()
{
}
bool Empty()
{
return 0 == vused_;
}
size_t Count()const
{
return vused_;
}
void Push(const T& t)
{
if(vused_ == vsize_)
{
Stack temp(2*vsize_ + 1);
while(temp.Count() < vused_)
{
temp.Push(v_[temp.Count()]);
}
temp.Push(t);
Swap(temp);
}
else
{
construct(v_+vused_,t);
++vused_;
}
}
void Pop()
{
if (vused_ == 0)
{
throw "pop from empty stack";
}
else
{
--vused_;
destroy(v_+vused_);
}
}
T& Top()
{
if (vused_ == 0)
{
throw "empty stack";
}
return v_[vused_-1];
}
};
说明:
1、去掉了第一个版本中的try语句
2、构造函数和拷贝构造函数及赋值函数更优雅。
3、异常安全性更强,在内存重分配过程中出现的异常,导致TOP等引用失效的情况将不复存在,属于commit-and-rollback级别的异常。