Can copy elision occur in catch statements?

后端 未结 3 1661
名媛妹妹
名媛妹妹 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:33

    Yes. If the catch catches the exception by reference, then there will not be copy (well, that is by definition).

    But I think that is not your question, and I believe the code which you've written is written on purpose with no mention of reference. If that is the case, then yes, even in this case, copy can be elided. Actually initialization of the variable in the catch is direct-initialization in theory. And copy in a direct-initialization can be elided by the compiler where it's possible.

    C++03 §8.5/14 reads,

    [...] In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized;

提交回复
热议问题