catch 块如何捕获对其他作用域中临时变量的引用

How can a catch block catch a reference to a temporary variable in an other scope?

本文关键字:变量 引用 作用域 何捕获 其他 catch      更新时间:2023-10-16

你可以试一试。下面的程序编译并运行流畅。构造函数中变量ex的地址与 catch 块中的临时变量 e 的地址不同。但是,您可能会注意到,B 行中 ex 的值是通过引用传递给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 对象 a 的析构函数?

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