Search code examples
c++assemblycompiler-optimizationnoexcept

How does noexcept in C++ change the assembly?


How does noexcept in C++ change the assembly? I tried a bit with small functions, in godbolt, but the assembly did not change.

float pi() 
//noexcept // no difference
{ return 3.14; }

int main(){
    float b{0};
    b = pi();
    return 0;
}

I am looking for a minimal working example, where I can see a change in the assembly due to noexcept.


Solution

  • Pretty simple examples can be constructed that involve destructors directly rather than introspection on noexcept status:

    void a(int);
    void b() noexcept;
    void c(int i) {
      struct A {
        int i;
        ~A() {a(i);}
      } a={i};
      b();
      a.i=1;
    }
    

    Here, the noexcept allows the initialization of a in the caller to be ignored, since the destructor cannot observe it.

    struct B {~B();};
    void f();
    void g() noexcept {
      B b1;
      f();
      B b2;
    }
    

    Here, the noexcept allows the omission of frame information needed in case the callee throws. This depends on the (very common) decision to not unwind the stack when calling std::terminate.