1

Consider the following code:

struct T {
  void f() noexcept { /* an arbitrary long piece of code */ }
};
void some_function() {
  T t{};
  try { t.f(); }
  catch(...) {
    std::cout << "Something is Wrong!!"; // An unreachable line of code
  }
}

Is there any level of optimization in Clang and GCC that removes the whole try/catch, and simply calls t.f() instead? Is there any specific switch for enabling/disabling this optimization?

Koosha
  • 1,492
  • 7
  • 19
  • 1
    For the first part of your question, why don't you just try it? – eesiraed Jun 17 '20 at 00:26
  • 2
    There's [no exception handling code generated even on `-O0` with GCC 10 or Clang 10](https://godbolt.org/z/P735sN). – Miles Budnek Jun 17 '20 at 00:27
  • @BessieTheCow How do I do that if I don't know how to read a compiled code? – Koosha Jun 17 '20 at 00:28
  • 2
    @Koosha Sure, but did you try? The lack of print statement is pretty obvious. – Yakk - Adam Nevraumont Jun 17 '20 at 00:29
  • 2
    If you can't read the generated assembly then take another approach. Profile your code with the `try`/`catch` then re-compile without it and profile again. See if there's a measurable performance difference. If not, then it doesn't really matter if the compiler generated exception handling code or not. – Miles Budnek Jun 17 '20 at 00:34
  • Actually, even if you can't read the generated assembly, you can still use tools to parse out an object file. Tools like `nm` or `objdump` should clearly show whether there's any code in there that references `std::cout`, or whether a literal string was compiled. This is something that can be easily observed without any particular knowledge of assembly. It should be very apparent whether the compiled object module contains the exception handling code, or not. – Sam Varshavchik Jun 17 '20 at 00:38
  • 4
    Use a compiler explorer like https://godbolt.org/ .... try making little changes and see what happens.... it is a good way to learn "enough" assembly – WilliamClements Jun 17 '20 at 00:56

0 Answers0