catch exception by pointer in C++(在 C++ 中通过指针捕获异常)
问题描述
我发现捕获异常有三种方式,有什么区别?
I found that there are three ways to catch an exception, what are the differences?
1) 按价值捕获;
2) 通过引用捕获;
3) 指针捕获;
我只知道按值捕获会调用对象的两个副本,按引用捕获会调用一个.那么如何通过指针捕获呢?何时使用指针捕获?除了抛出一个对象,我可以像这样抛出一个指向对象的指针吗?
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;
}
推荐答案
推荐的方式是按值抛出,按引用捕获.
您的示例代码抛出了一个指针,这是一个坏主意,因为您必须在 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++ 编码标准一书中很好地解释了这一点,我对此进行了解释.
请参阅C++ 编码标准:按值抛出,按引用捕获.
这篇关于在 C++ 中通过指针捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中通过指针捕获异常


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30