Whats the right approach for error handling in C++(在 C++ 中处理错误的正确方法是什么)
问题描述
一种是使用 C++ 异常:try catch 块.但是在引发异常时释放动态内存将是一个问题.
One is to use C++ exceptions: try catch blocks. But freeing dynamic memory will be an issue when an exception is raised.
二是使用C风格:errno变量
Second is to use C style: errno variable
第三个只是在错误时返回 -1,成功时返回 0 :)
Third is just to return -1 on error and 0 on success :)
中型项目应该选择哪种方式,为什么?还有其他更好的方法......?
Which way should be chosen for a mid-size project and why? Any other better approach..?
推荐答案
但在引发异常时释放动态内存将是一个问题.
But freeing dynamic memory will be an issue when an exception is raised.
不,不是.std::vector 完成.
这里的概念称为范围绑定资源管理 (SBRM),也称为更常见(和笨拙)的名称资源获取即初始化 (RAII).基本上,所有资源都包含在某个对象中,该对象将清理析构函数中的资源(始终保证为自动分配的对象运行).因此,无论该函数是否正常存在或通过异常存在,都会运行析构函数并清理您的资源.
The concept here is called Scope-Bound Resource Management (SBRM), also known by the much more common (and awkward) name Resource Acquisition Is Initialization (RAII). Basically, all resources are contained in some object which will clean up the resource in the destructor (which is always guaranteed to be run for an automatically allocated object). So whether or not the function exists normally or via exception, the destructor is run and your resource is cleaned up.
永远不要在需要明确释放的地方进行分配,使用容器和智能指针.
Never do an allocation where you need to free it explicitly, use containers and smart pointers.
这篇关于在 C++ 中处理错误的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中处理错误的正确方法是什么
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
