异常对象生命周期 [英] Exception object lifetime

查看:149
本文介绍了异常对象生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何创建异常对象?以及为什么处理程序函数参数可以是非const引用?



例如:

  class E {
public:
const char * error;
E(const char * arg):error(arg){
cout< E()的构造函数:;}

E(const E& m){
cout< 复制构造函数E(E& m):;
error = m.error;
}
};



int main(){
try {
throw E(Out of memory);

}
catch(E& e){cout<< e.error;}

}

b>
E()的构造函数:在内存中出现



所以我有 throw E ) E(out of memory)只是一个临时对象,除了 E (out of memory),因为没有调用复制构造函数。所以即使这个 E(out of memory)只是一个临时对象,我有一个处理程序接受一个非const引用。

$ b $

解决方案


您可以向我解释为什么会是这样吗?想要知道如何创建异常对象?


执行此操作时:

  throw E(Out of memory); 

您在本地创建一个对象(类型E)。抛出的过程将此对象复制到标准未定义的某个私有内存位置。因此,被抛出的对象必须是可复制的。



注意:编译器允许优化副本并直接在私有位置创建副本。因此,它不被复制的事实是因为编译器优化了离开副本(所以它不是本地)。尝试使复制构造函数私有,现在它将无法编译。


为什么处理函数参数可以是非const引用?


当您抓取对象时:

  catch(E& e)

您正在获取对象在私人位置的引用它被复制到。它不是一个const(或临时)值,所以你可以有一个正常的引用。


I want to know how the exception object is created ? and why the handler function parameter can be a non-const reference?

For example:

class E{
    public:
    const  char * error;
    E(const char* arg):error(arg){
    cout << "Constructor of E(): ";}

    E(const E& m){
        cout << "Copy constructor E(E& m): " ;
       error=m.error;
    }
};



int main(){
try{
    throw E("Out of memory");

}
catch(E& e){cout << e.error;}

}

Output: Constructor of E(): Out of memory

so I have throw E("out of memory") and E("out of memory")is just a temporary object and no object has been created except E("out of memory") because no copy constructor has been invoked. so even though this E("out of memory") is just a temporary object, I have a handler that take a non-const reference.

Can you explain to me why this is possible?

解决方案

want to know how the exception object is created ?

When you do this:

throw E("Out of memory");

You create an object (of type E) locally. The processes of throwing copies this object to some private memory location not defined by the standard. Thus the object being thrown must be copyable.

Note: the compiler is allowed to optimize out the copy and create it directly in the private location. So the fact that it is not copied is because the compiler optimized away the copy (so it is not local anymore). Try making the copy constructor private and now it will fail to compile.

and why the handler function parameter can be a non-const reference ?

When you catch the object:

catch(E& e)

You are getting a reference to the object at the private location it was copied to. Its not a const (or temporary) value so you can have a normal reference to it.

这篇关于异常对象生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆