Confusion over non-throw functions

I have 2 questions about non-throwing functions:

  • Why make a function without metaling?

  • How to make a non-throwing function? If the code inside the function really can throw, should I still do it not to drop it?

Here is an example:

void swap(Type t1, Type t2) throw()
{
    //swap
}

If the code in swapwill not be thrown at all, should I add throw()? Why?

+5
source share
2 answers

throw()(or noexceptin C ++ 11) is useful for two reasons:

  • This allows the compiler to be more aggressive in its optimizations.
  • It tells function users that they can use this function in their own non-throwing functions.

. , operator= non-throwing swap().

, . .

, noexcept , , . , (, VS ), , - . :

void f() noexcept
{
  a();
  b();
}

a() b() , , b() a(), , .

EDIT: : ?

, . :

class C
{
  C* CreateInstance()
  {
    return new C();
  }
}

new std::bad_alloc, CreateInstance() . try-catch, , try, ? :

C* CreateInstance()
{
  try
  {
     return new C();
  }
  catch (...)
  {
     return null;
  }
}

, , CreateInstance() null? , , . , std::bad_alloc , , .

: , . - .

+4

?

, - , .

? , ?

, , try, .

void swap(T t1, T t2) noexcept {
  try {
    // ....
  } catch (const std::exception& ex) {
    // ....
  } catch (...) {
    // ....
  }

}

, , . , , . , , , . ++ 11 noexcept .

+2

All Articles