c++ - catch 语句中可以发生复制省略吗?

标签 c++ exception optimization copy-elision

考虑一个带有带有副作用的复制构造函数的异常类。

编译器能否在此处跳过调用复制构造函数:

try {
    throw ugly_exception();
}
catch(ugly_exception) // ignoring the exception, so I'm not naming it
{ }

这个怎么样:

try {
    something_that_throws_ugly_exception();
}
catch(ugly_exception) // ignoring the exception, so I'm not naming it
{ }

(是的,我知道这一切都很丑陋,这是受 another question 启发的)

最佳答案

是的,在 throw 和 catch 时都可以省略。对于捕获,仅当 catch 子句中指定的类型与异常对象的类型相同(除了 cv 限定)时,才可以省略它。有关更正式和详细的描述,请参阅 C++11 12.8/31。

...This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

...

  • in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object

...

  • when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.

关于c++ - catch 语句中可以发生复制省略吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7401521/

相关文章:

c++ - 构造函数定义和声明不匹配

c++ - AIX 5.3 上的跨共享库问题异常

c# - XMLTextWriter C#,未找到标准xml的数据

c++ - 来自 Qt 的 Bizzare 错误

c++ - 如何使用 FTGL 显示文本固定位置 2d?

c++ - Cplex 的双值排序

java - Java中并发写入时如何通过异常发出关于 'retry exceeded'的信号?

c++ - 什么是复制省略和返回值优化?

java - 施工时间不满意

python - Matlab 的 fminimax 是否适用帕累托最优?