>
>
>
V816. It is more efficient to catch exc…


V816. It is more efficient to catch exception by reference rather than by value.

The analyzer detected a construct that can be optimized. It is more efficient to catch exceptions by reference rather than by value: it will help avoid copying objects.

Consider the following example:

catch (MyException x)
{
  Dump(x);
}

This code can be improved a bit. In its original form, a new object of type MyException is created when catching the exception. It can be avoided by catching the exception by reference. It makes even more sense when the object is "heavy".

The fixed version of the code:

catch (MyException &x)
{
  Dump(x);
}

Catching exceptions by reference is good not only from the optimization's viewpoint; it helps avoid some other issues as well – for example slicing. However, discussion of these issues is beyond the scope of this diagnostic's description. Errors related to slicing are detected by diagnostic V746.

The pros of catching exceptions by reference are discussed in the following sources:

This diagnostic is classified as:

  • CERT-ERR61-CPP