Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Because the variable declared by the exception-declaration is copy-initialized, it is possible to slice the exception object as part of the copy operation, losing valuable exception information , and leading to incorrect error recovery. For instance, all exception types provided by the Standard Template Library inherit from std::exception, which has a virtual member function, what(), that returns implementation-defined information about the exception object. If the exception variable declared by the catch handler was sliced from the exception object created by the throw expression, calling what() on the catch handler exception variable would not result in calling what() on the exception object. For more information about object slicing, see OOP51-CPP. Do not slice derived objects.

Always catch exceptions by lvalue reference unless the type is a trivial type. For reference, the C++ Standard, [basic.types], paragraph 9 [ISO/IEC 14882-2014], defines trivial types as:

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types....   Scalar typesScalar types, trivial class types, arrays of such types and cv-qualified versions of these types are collectively called trivial types.

The C++ Standard, [class], paragraph 6, defines trivial class types as:

A trivially copyable class is a class that:
  — has no non-trivial copy constructors,
  — has no non-trivial move constructors,
  — has no non-trivial copy assignment operators,
  — has no non-trivial move assignment operators, and
  — has a trivial destructor.
A trivial class is a class that has a default constructor, has no non-trivial default constructors, and is trivially copyable. [Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes. — end note]

...

Object slicing can result in abnormal program execution. This generally is not a problem for exceptions, but it can lead to unexpected behavior depending on the assumptions made by the exception handler.

...

[ISO/IEC 14882-2014]

Subclause 3.9, "Types"
Clause 9, "Classes"
Subclause 15.1, "Throwing an Exception"
Subclause 15.3, "Handling an Exception" 

[MISRA 08]Rule 15-3-5

 

...

Image Modified Image Modified Image Modified