在catch块异常中无意义使用按引用传递语法? [英] Meaningless use of pass by reference syntax in catch block- exception?

查看:74
本文介绍了在catch块异常中无意义使用按引用传递语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例代码:

#include<iostream>
using namespace std;

class Test{ public: int set;};
Test T;

int main()
{
    T.set = 100;
    try{
        throw T;
    }
    catch(Test &T)
    {
        T.set = 0;
    }
    cout<<T.set<<endl;
    return 1;
}

在这里,我通过引用捕获了抛出的T对象,并在捕获块。为什么 T 对象在 catch 之后仍然显示 100 块?在这种情况下,按值传递时引用语法的用途是什么?

Here I am catching the thrown T object by reference and modifying its value inside the catch block. Why does the T object still prints 100 after the catch block? What is the use of reference syntax in this case over pass by value?

编译器:gcc 5.1.0

compiler: gcc 5.1.0

推荐答案

您正在通过引用捕获异常对象,但没有这样抛出它。

You are catching the exception object by reference, but not throwing it as such.

异常是总是按值扔 ,因为它们必须分配到进程内存的特殊区域中,不受堆栈展开的影响。

Exceptions are always "thrown by value", because they must be allocated in a special region of your process's memory that is immune to the effects of stack unwinding.


[C ++ 14:15.1 / 3]:抛出异常,将初始化为(8.5、12.8)临时对象,称为例外对象。临时变量是一个左值,用于初始化在匹配的 handler (15.3)中声明的变量。 [..]

[C++14: 15.1/3]: Throwing an exception copy-initializes (8.5, 12.8) a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable declared in the matching handler (15.3). [..]

这是一条通用规则,旨在解决更为常见的情况其中 T 实际上是 try 块本身或其封装功能的本地变量。如果未复制它,将无法从调用范围中捕获它。

This is a general rule that is designed to account for the far more common case in which T is actually local to either the try block itself or its encapsulating function. It would be impossible to catch it from calling scopes if it were not copied.

我们通过引用捕获异常对象,这样您就不必不必要地复制 已经复制的 T 。当您的异常处于继承层次结构中时,它还可以防止切片。有时人们用它来变异异常对象,然后再将其重新扔给调用范围,尽管这似乎很罕见。

We catch the exception object by reference so that you don't needlessly copy again the already-copied T. It also prevents slicing when your exceptions are in an inheritance heirarchy. Sometimes people use it to mutate the exception object before re-throwing it to calling scopes, though this appears to be a rarity.

通过引用 const 与通过引用- const 捕获任何其他事物具有相同的好处:它确保您不会改变异常。如果您不扔掉它,那么这里没有实际的好处,但是如果像我一样,您默认编写 const 作为防止错误的安全措施,则没有理由使用它。

Catching it by reference-to-const has the same benefit as catching any other thing by reference-to-const: it ensures that you do not mutate the exception. If you're not rethrowing it then there's no practical benefit here but if, like me, you write const by default as a fail-safe against mistakes, there's no reason not to use it.

这篇关于在catch块异常中无意义使用按引用传递语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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