🐭 C++ 中的异常

异常是一种通用的应用程序错误处理方式,很多编程语言都支持,异常的高明之处是能将错误检测与错误处理相分离。C++ 中的异常类继承关系大概如下图:
「C++17 Standard Library Quick Reference 2E」
stdexceptions.png

🐂 异常安全声明

对于异常,我们感兴趣的往往是一个函数是否会抛出异常,而不是该函数会抛出什么类型的异常,因为随着时间的推移函数抛出的异常类型会变得不确定。对于异常安全的函数,也就是确定不会抛出异常的函数,我们可以明确的使用 noexcept 关键字标识出来。

  1. 给客户端提示,对代码编写友好
  2. 给编译器提示,对代码优化友好

代码示例 :

  1. #include <iostream>
  2. // noexcept specifier
  3. // C++17 redefined the 'throw()' as exact equivalent of 'noexcept(true)'
  4. int fun0(int x) throw(); // exceptions free
  5. int fun1(int x) noexcept; // exceptions free
  6. int fun2(int x) noexcept(true); // exceptions free
  7. int fun3(int x) noexcept(false); // exceptions
  8. int fun4(int x); // exceptions
  9. // by default
  10. // 1. all memory deallocation functions are exceptions free, such as:
  11. // operator delete and operator delete[]
  12. // 2. all destructors user defined or compiler generated are implicitly exceptions free
  13. struct Job {
  14. ~Job(){}; // exceptions free
  15. };
  16. int main() {
  17. using std::cout;
  18. cout.setf(std::ios_base::boolalpha);
  19. // noexcept operator
  20. cout << "fun0 noexcept? " << noexcept(fun0(1)) << '\n'; // true
  21. cout << "fun1 noexcept? " << noexcept(fun1(1)) << '\n'; // true
  22. cout << "fun2 noexcept? " << noexcept(fun2(1)) << '\n'; // true
  23. cout << "fun3 noexcept? " << noexcept(fun3(1)) << '\n'; // false
  24. cout << "fun4 noexcept? " << noexcept(fun4(1)) << '\n'; // false
  25. return 0;
  26. }

C++ 异常确实会影响性能,这就是很多 C++ 最佳实践都禁止使用异常的缘由。编译器对于异常安全的函数会生成更高效的代码,因为不用考虑异常发生时候的调用栈展开问题。但是,异常仍然是 C++ 开发中错误处理的最好方式。 :::tips C++ 的零开销原则 (zero overhead principle):

  1. 你不用为没有使用的语言特性而付出任何代价
  2. 你使用的语言特性,至少与你自己手动实现一样高效

目前只有 RTTI 与 exception 违反了 C++ 的零开销原则,但是它们都是可选的

  1. 禁用 RTTI ‘-fno-rtti‘
  2. 禁用 exception ‘-fno-exceptions‘ :::

    🐯 异常安全的应用

    现代 C++ 移动语义的引入,使得移动对象的效率大大提升,但是当移动操作不是异常安全的时候,会退回到拷贝操作,进而保证异常安全。另外,条件异常安全也比较常用,就是通过基本类型操作的异常安全来推导出复合类型操作的异常安全,std::swap 就是一个典型。
    代码示例 : ```cpp

    include

struct X { X(int x = 0) : x{x} {} X(X &&) noexcept { std::cout << “calls X’s move ctor\n”; } X(const X &) noexcept { std::cout << “calls X’s copy ctor\n”; } // conditionally noexcept void swap(X &x) noexcept(noexcept(std::swap(x, x.x)) &&noexcept(std::swap(y, x.y))) { std::swap(x, x.x); std::swap(y, x.y); } int x; char y_{‘y’}; };

struct Y { Y() = default; Y(Y &&) { std::cout << “calls Y’s move ctor\n”; } Y(const Y &) { std::cout << “calls Y’s copy ctor\n”; } };

int main() { X x1; Y y1; X x2 = std::move_if_noexcept(x1); // calls X’s move ctor Y y2 = std::move_if_noexcept(y1); // calls Y’s copy ctor

X x3{3}; X x4{4}; std::cout << std::boolalpha << noexcept(std::declval().swap(x3)) << ‘\n’; // true x3.swap(x4); std::cout << x3.x << ‘ ‘ << x4.x << ‘\n’; // 4 3

return 0; } ``` :::tips 注意上面 std::declval 的使用,std::declval 往往与 decltype 一起使用,可以避免创建对象 :::

🐰 总结

  1. noexcept 是函数接口的一部分
  2. noexcept 函数对编译器优化友好
  3. noexcept 声明对移动操作,交换操作是很有意义的
  4. 绝大多数函数默认不是异常安全的,除了几类特殊的函数