Exception slicing - is this due to generated copy constructor?

后端 未结 4 1659
抹茶落季
抹茶落季 2020-12-15 10:56

I\'ve just fixed a very subtle bug in our code, caused by slicing of an exception, and I now want to make sure I understand exactly what was happening.

Here\'s our b

4条回答
  •  被撕碎了的回忆
    2020-12-15 11:10

    C++ never ceases to amaze me. I would have lost a lot of money had this been a bet on what was the behaviour!

    The exception object is first copied to a temporary and you should have used throw. To quote the standard 15.1/3:

    A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from "array of T" or "function returning T" to "pointer to T" or "pointer to function returning T",respectively.

    I think this gives rise to a very useful coding standard rule:

    Base classes of an exception hierarchy should have a pure virtual destructor.

    or

    The copy constructor for a base class in an exception hierarchy shall be protected.

    Either achieves the goal that the compiler will warn when you try to "throw e" since in the first case you cannot create an instance of an abstract class and the second because you cannot call the copy constructor.

提交回复
热议问题