败犬日报 2025-03-09
1. 异常会导致二进制膨胀
写了异常会多一堆二进制代码来处理异常,一些项目禁止 RTTI 和异常都是这个理由。
例如 LLVM https://llvm.org/docs/CodingStandards.html#do-not-use-rtti-or-exceptions:
Do not use RTTI or Exceptions
In an effort to reduce code and executable size, LLVM does not use exceptions or RTTI (runtime type information, for example, dynamic_cast<>).
That said, LLVM does make extensive use of a hand-rolled form of RTTI that use templates like isa<>, cast<>, and dyn_cast<>. This form of RTTI is opt-in and can be added to any class.
当然允许异常的项目同样也有很多,异常更简单省事。
不用异常可以用 std::expected
或类似的设计替代。
一个 cppcon 讲了如果返回错误码的代码过多,关闭 rtti 使用异常替换同样的逻辑可以做到更小的二进制体积。https://www.bilibili.com/video/BV14YyfYhE3C 第一集