Confusion around noexcept

After watching many videos while reading the book, I am at a loss when and when not to use noexcept.

All books say that you should only use noexcept when the function WILL NEVER EVER quit.

I think it should be used differently. Many people say that functions that allocate shouldn't be excluded, but what if I don't want to catch these errors and the call std::terminate

is acceptable?

In short, you shouldn't use functions that will never throw, or on all functions other than those you would like to exclude from.

IMHO some exceptions do not need to be caught (i.e. from memory, etc.)

+3


source to share


1 answer


The marker noexcept

is the guarantor from the developer to the compiler that the function will never throw.

So, you should add it to the functions that you know Should never throw. If these functions do for some obscure and unknowable reason, the only thing the compiler can do is to terminate the application (since you guaranteed something that shouldn't have happened). Note: from a function marked with noexcept, you probably shouldn't call another function unless it is also marked with noexcept (just like const correctness, you don't need to have any error)

Where should you use it:

  swap()   methods/functions. 
           Swap is supposed to be exception safe.
           Lots of code works on this assumption.

  Move Constructor
  Move Assignment.
           The object you are moving from should already be
           fully formed so moving it is usually a processes of
           swapping things around.

           Also be marking them noexcept there are certain 
           optimizations in the standard library that can be used.

     Note: This is usually the case.
           If you can not guarantee that move/swap semantics are 
           exception safe then do not mark the functions as noexcept.

      



You don't want to call terminate for all exceptions. In most cases, I allowed the exception to unwind the stack, call the destructors and properly free resources.

It is not caught, then the application will terminate.

But most complex applications need to be exception-resistant. Catch cancel triggered task log except and wait for next command. Sometimes you still want to quit, but just because my smear operation on a graphical application is failing doesn't mean that I want the application to quit inhumanly. I would prefer that the smudge operation be left re-asserted and the application goes back to normal (so I can save the exit and restart).

+3


source







All Articles