catch 块如何捕获对其他作用域中临时变量的引用
How can a catch block catch a reference to a temporary variable in an other scope?
你可以试一试。下面的程序编译并运行流畅。构造函数中变量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
表达式在离开本地范围之前将引发的对象复制到安全位置。该语言没有确切说明它的存储位置,只是说这必须以某种方式工作(细节留给实现)。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 如果非动态变量被指针引用,何时超出范围?
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 为什么C++可以使用未初始化的成员变量(引用或指针 *NOT 值复制*)来初始化其父类的成员变量
- 地址运算符是否返回变量引用的对象的地址
- 未在另一个函数中设置变量引用的问题
- 英特尔样式内联程序集和 AT&T 样式中的变量引用,C++
- 将成员变量引用为类成员
- 从静态变量引用非静态变量会使非静态变量先于静态变量进行析构函数
- 何时解析 C++11 lambda 表达式中的变量引用
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- C++强制对变量引用进行编译优化,使之成为直接的
- Boost变量引用和相等比较
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员
- 为什么要在Java中生成变量引用数组
- 捕获和调试对移动lambda内部局部变量引用的无效使用
- 在变量初始化后更改变量引用
- 从'C'程序中提取变量定义和变量引用