C++函数后面的throw()

来源:互联网 发布:windows event id 编辑:程序博客网 时间:2024/05/18 11:01

它是函数提供者和使用者的一种君子协定,标明该函数不抛出任何异常。
之所以说是君子协定,是因为实际上内部实现是需要人肉确保。
如果一个标明throw()的函数内部发生了throw:
1,如果内部直接throw something,编译器会发现并指出;
2. 如果是内部调用了一个可能throw something的函数,编译器无法发现,运行时一旦这个内部的函数throw,程序会abort。

这是异常规范,只会出现在声明函数中,表示这个函数可能抛出任何类型的异常,例如:
void GetTag() throw(int);表示只抛出int类型异常
void GetTag() throw(int,char);表示抛出in,char类型异常
void GetTag() throw();表示不会抛出任何类型异常
void GetTag() throw(...);表示抛出任何类型异常

void GetTag() throw(int);表示只抛出int类型异常
并不表示一定会抛出异常,但是一旦抛出异常只会抛出int类型,如果抛出非
int类型异常,调用unexsetpion()函数,退出程序。

假如你加一个throw()属性到你的永远不会抛出异常的函数中,编译器会非常聪明的知道代码的意图和决定优化方式
template <class T>
class auto_ptr
{
private:    
T* ap;
public:    
// constructor & destructor ----------------------------------- (1)    
explicit auto_ptr (T* ptr = 0) throw() : ap(ptr) { }    
~auto_ptr() throw()
{
delete ap;
}    
// Copy & assignment --------------------------------------------(2)    
auto_ptr (auto_ptr& rhs) throw() : ap(rhs.release()) { }
template <class Y>    
auto_ptr(auto_ptr<Y>& rhs) throw() : ap(rhs.release()) { }    
auto_ptr& operator= (auto_ptr& rhs) throw()
{
     reset(rhs.release());
     return *this;
}
template <class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()
{
     reset(rhs.release());
     return *this;
}
// Dereference----------------------------------------------------(3)
T& operator*() const throw()
{
     return *ap;
}
T* operator->() const throw()
{
     return ap;
}
// Helper functions------------------------------------------------(4)
// value access
 T* get() const throw ()
{
     return ap;
}
// release ownership
T* release() throw()
{
     T* tmp(ap);
     ap = 0;
     return tmp;
}
// reset value
void reset (T* ptr=0) throw()
{
     if (ap != ptr){
         delete ap;
         ap = ptr;
     }
}
// Special conversions-----------------------------------------------(5)
template<class Y>
struct auto_ptr_ref
{
     Y* yp;
     auto_ptr_ref(Y* rhs) : yp(rhs) { }
};
auto_ptr(auto_ptr_ref<T> rhs) throw() : ap(rhs.yp) { }
auto_ptr& operator= (auto_ptr_ref<T> rhs) throw()
{
     reset(rhs.yp);
     return *this;
}
template <class Y>
operator auto_ptr_ref<Y>() throw()
{
     return auto_ptr_ref<Y>(release());
}
template <class Y>
operator auto_ptr<Y>() throw()
{
     return auto_ptr<Y>(release());
}

0 0
原创粉丝点击