Can copy elision occur in catch statements?

后端 未结 3 1566
名媛妹妹
名媛妹妹 2021-01-05 02:13

Consider an exception class with a copy constructor with side-effects.

Can a compiler skip calling the copy constructor here:

try {
    throw ugly_ex         


        
3条回答
  •  时光说笑
    2021-01-05 02:32

    I think this is specifically permitted. For C++03, 15.1/3 says:

    A throw-expression initializes a temporary object, called the exception object,

    and 12/15 says:

    when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the tempo- rary object directly into the target of the omitted copy

    So, the secret hiding place where in-flight exceptions are kept, is defined by the standard to be a temporary, and hence is valid for copy-elision.

    Edit: oops, I've now read further. 15.1/5:

    If the use of the temporary object can be eliminated without changing the meaning of the program except for the execution of constructors and destructors associated with the use of the temporary object (12.2), then the exception in the handler can be initialized directly with the argument of the throw expression.

    Doesn't get much clearer.

    Whether it actually will... if the catch clause were to re-raise the exception (including if it called non-visible code that might do so), then the implementation needs that "temporary object called the exception object" still to be around. So there might be some restrictions on when that copy elision is possible. Clearly an empty catch clause can't re-raise it, though.

提交回复
热议问题