gpt4 book ai didi

c++ - C++中的临时对象如何影响效率?

转载 作者:行者123 更新时间:2023-12-01 22:24:07 27 4
gpt4 key购买 nike

我读过 CodeProject 上的一篇文章 http://www.codeproject.com/Tips/103648/C-Tip-How-to-eliminate-Temporary-Objects .

Complex y,z;
Complex x=y+z; /* initialization instead of assignment */

我很困惑为什么第二条语句不创建临时对象?编译器是如何工作的?

最佳答案

C++ 中有一条规则,如果临时变量直接用于初始化,则允许编译器忽略它们。
无论如何,利用其余地,编译器可以在没有这条规则的情况下优化示例,这具有相同的效果。

12.8 Copying and moving class objects §32

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a classobject, even if the copy/move constructor and/or destructor for the object have side effects. In such cases,the implementation treats the source and target of the omitted copy/move operation as simply two differentways of referring to the same object, and the destruction of that object occurs at the later of the timeswhen the two objects would have been destroyed without the optimization.123 This elision of copy/moveoperations, called copy elision, is permitted in the following circumstances (which may be combined toeliminate multiple copies):
— in a return statement in a function with a class return type, when the expression is the name of anon-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualifiedtype as the function return type, the copy/move operation can be omitted by constructingthe automatic object directly into the function’s return value
— in a throw-expression, when the operand is the name of a non-volatile automatic object (other thana function or catch-clause parameter) whose scope does not extend beyond the end of the innermostenclosing try-block (if there is one), the copy/move operation from the operand to the exceptionobject (15.1) can be omitted by constructing the automatic object directly into the exception object
— when a temporary class object that has not been bound to a reference (12.2) would be copied/movedto a class object with the same cv-unqualified type, the copy/move operation can be omitted byconstructing the temporary object directly into the target of the omitted copy/move
— 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 omittedby treating the exception-declaration as an alias for the exception object if the meaning of the programwill be unchanged except for the execution of constructors and destructors for the object declared bythe exception-declaration.

关于c++ - C++中的临时对象如何影响效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com