Exception C++中讨论的异常安全堆栈的,封装内存管理的版本,使用私有继承的方式复用

本文介绍了一个自定义栈类的实现细节,包括构造函数、拷贝构造函数、赋值操作符等,并通过异常安全的设计增强了内存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#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级别的异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值