gpt4 book ai didi

c++ - std::move() 或其在局部变量上的显式等效项是否允许省略?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:43 26 4
gpt4 key购买 nike

例如:

Big create()
{
Big x;
return std::move(x);
// return static_cast<typename std::remove_reference<T>::type&&>(t) // why not elide here?
}

假设应用 std::move()返回局部变量会抑制 move 语义,因为编译器通常无法对函数的内部工作做出任何假设,如果不需要这些假设,例如当:

  1. std::move(x)是内联的(可能总是)
  2. std::move(x)写成:static_cast<typename std::remove_reference<T>::type&&>(t)

根据当前标准,允许实现应用 NRVO...

— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler (18.3)) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call’s return object

显然,1) 和 2) 都不符合条件。除了使用 std::move()返回一个局部变量是多余的,为什么这个限制是必要的

最佳答案

您应该清楚“允许省略”的确切含义。首先,编译器可以在“as-if”规则下做任何它想做的事情。也就是说,编译器可以吐出它想要的任何程序集,只要该程序集的行为正确即可。这意味着编译器可以省略它想要的任何构造函数,但它必须证明无论是否调用构造函数,程序的行为都是相同的。

那么为什么省略的特殊规则?好吧,在这些情况下,编译器可以省略构造函数调用(因此也省略析构函数调用) 证明行为是相同的。这非常有用,因为有很多类型的构造函数非常重要(比如 string),而且实践中的编译器通常无法证明它们可以安全地省略(在合理的时间范围内)(过去,甚至不清楚优化堆分配是否合法,因为它基本上是全局变量的突变)。

因此,出于性能原因,我们希望省略。但是,就行为而言,它基本上是在标准中指定一个特例。特殊情况越大,我们引入标准的复杂性就越高。因此,目标应该是使省略的允许情况足够广泛以涵盖我们关心的有用案例,但不会更广泛。

您的处理方式是:为什么不让特殊情况尽可能大?实际上,情况恰恰相反。为了扩大允许省略的情况,需要证明它是非常值得的。

关于c++ - std::move() 或其在局部变量上的显式等效项是否允许省略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45553797/

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