通过C ++中的指针捕获异常 [英] catch exception by pointer in C++

查看:142
本文介绍了通过C ++中的指针捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有三种方法来捕获异常,有什么区别?

I found that there are three ways to catch an exception, what are the differences?

1)按价值获取;

2)通过引用捕获;

2) catch by reference;

3)catch by pointer;

3) catch by pointer;

知道通过值捕获将调用对象的两个副本,通过引用捕获将调用一个。那么指针如何捕捉呢?何时使用catch指针?除了抛出一个对象之外,我可以把这个指针指向一个对象吗?

I only know that catch by value will invoke two copies of the object, catch by reference will invoke one. So how about catch by pointer? When to use catch by pointer? In addition to throw an object, can I throw a pointer to an object like this?

class A {}

void f() {

  A *p = new A();
        throw p;


}


推荐答案

p> 推荐的方法是通过引用引用来引用值。

您的示例代码抛出一个指针,这是一个坏主意,你必须在catch站点处理内存。

Your example code throws a pointer, which is a bad idea since you would have to manage memory at the catch site.

如果你真的觉得你应该抛出一个指针,使用一个智能指针,如 shared_ptr

If you really feel you should throw a pointer, use a smart pointer such as shared_ptr.

无论如何,Herb Sutter和Alexei Alexandrescu解释说,他们的C ++编码标准书,我已经释义了。

Anyway, Herb Sutter and Alexei Alexandrescu explain that really well in their C++ Coding Standards book which I paraphrased.

请参阅 C ++编码标准:按价值投入,按参考资料

这篇关于通过C ++中的指针捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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