Copy elision
参考
- https://en.cppreference.com/w/cpp/language/copy_elision
- https://www.youtube.com/watch?v=PTCFddZfnXc 2024 年 6 月 26 日:这个视频讲了 GCC 的新
-Wnrvo编译参数。
C++17 prvalue semantics (“guaranteed copy elision”)
返回值(或函数参数)的位置,如果表达式是纯右值,且返回值(或函数参数)需要的也是同一类型的纯右值,那么标准就要求省略复制和移动。不过,为了让语义检查通过,要构造对象的析构函数必须在此处可以访问,尽管在完成优化之后并不会用到析构函数。
T f()
{
return U(); // constructs a temporary of type U,
// then initializes the returned T from the temporary
}
T g()
{
return T(); // constructs the returned T directly; no move
}
T x = T(T(f())); // x is initialized by the result of f() directly; no move
The C++17 core language specification of prvalues and temporaries is fundamentally different from that of earlier C++ revisions: there is no longer a temporary to copy/move from. Another way to describe C++17 mechanics is “unmaterialized value passing” or “deferred temporary materialization”: prvalues are returned and used without ever materializing a temporary.
非强制的 copy/move elision
编译器一些场景可以对 copy/move 进行省略,但不是强制的(实测 gcc 和 clang 在默认优化等级下就会使用这项优化,而 MSVC 则是在 /O2 才会启用这项优化)。当这项优化发生时,复制 / 移动构造函数必须是可用的,尽管不会被实际执行。

