2

你可以试一试。下面的程序编译并运行顺利。ex构造函数中变量的地址e与 catch 块中的临时变量不同。但是您可能会注意到exB 行中的值是通过e引用传递给的。谁能解释发生了什么?

#include<cstring>
#include<iostream>


using std::string;
using std::endl;
using std::cout;

class ThrowException;
ThrowException* TE_ptr;

class ThrowException{

    private:
        string msg;
        int b;
    public:
        ThrowException(string m="Unknown exception",int factor=0) throw(string,const char*);
        ~ThrowException(){        cout<<"destructor get called."<<endl;}
        friend std::ostream& operator<<(std::ostream& os,const ThrowException&TE);
};

ThrowException::ThrowException(string m, int f) throw(string,const char*):msg(m),b(f){
    cout<<"msg="<<msg<<'\n'<<"b="<<b<<endl;
    TE_ptr=this;
    if(b==1){
        string ex("b=1 not allowed.");
        cout<<"The address of e in constructor is "<<&ex<<endl;      //A
        throw ex;
    }
}

std::ostream&operator<<(std::ostream&os, const ThrowException &TE){
    os<<TE.msg<<'\n'<<TE.b<<endl;
}
int main(){

    try{
        ThrowException a("There's nothing wrong.", 1);
    }catch(string &e){             //B
        cout<<"The address of e in first catch block is "<<&e<<endl;        //C
        cout<<"The content resided in the momery block pointed to by TE_ptr is "<<*TE_ptr<<endl;
    }

}

另一个我想问的问题是 ThrowException 对象的析构函数什么时候被调用?

4

1 回答 1

7

表达式在离开本地范围之前将throw抛出的对象复制到安全的地方。该语言并没有确切说明它的存储位置,只是它必须以某种方式工作(细节留给实现)。

于 2012-05-01T08:44:33.660 回答