gpt4 book ai didi

c++ - 为什么不总是应用 RVO/NRVO?

转载 作者:行者123 更新时间:2023-11-30 01:15:55 24 4
gpt4 key购买 nike

返回值优化机制的简短(可能过时且过于简单)总结如下 this :

an implementation may create a hidden object in the caller's stack frame, and pass the address of this object to the function. The function's return value is then copied into the hidden object (...) Around 1991, Walter Bright invented a technique to minimize copying, effectively replacing the hidden object and the named object inside the function with the object used for holding the result [1]

由于这是一个在 SO 上被广泛讨论的话题,我将只链接最完整的 QA我发现。

我的问题是,为什么不总是应用返回值优化?更具体地说(根据 [1] 中的定义)为什么这种替换不总是发生每次函数调用,因为函数返回类型(因此堆栈大小)总是在编译时已知,这似乎是一个非常有用的特性。

最佳答案

显然,当按值返回左值时,没有办法不进行复制。所以,让我们只考虑局部变量。应用于局部变量的一个简单原因是通常不清楚要返回哪个对象。考虑这样的代码:

T f(Args... args) {
T v1{some_init(args)};
T v2{some_other(args)};
bool rc = determine_result(v1, v2);
return rc? v1: v2;
}

在创建局部变量 v1v2 时,编译器无法判断将返回哪个,因此可以就地创建。

另一个原因是复制/移动构建和销毁可能会产生有意的副作用。因此,希望有方法来抑制复制省略。在引入复制省略时,已经有很多 C++ 代码可能依赖于要制作的某些拷贝,即只有少数情况符合复制省略的条件。

关于c++ - 为什么不总是应用 RVO/NRVO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709720/

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