gpt4 book ai didi

operator-overloading - C++0x T operator+(const T&, T&&) 模式,还需要移动吗?

转载 作者:行者123 更新时间:2023-12-04 11:59:01 24 4
gpt4 key购买 nike

前段时间有人告诉我,实现二元运算符的常用模式需要一个最终的 move在返回中。

Matrix operator+(const Matrix &a, Matrix &&b) {
b += a;
return std::move(b);
}

但是现在有一个特殊规则,在 return 中编译器可能会将返回值视为临时值,然后就没有必要了——一个简单的 return b就足够了。

但话又说回来, b在这个函数中有一个名字,因此,它是一个 LValue——这阻碍了编译器将它视为一个临时值,而 move是必须的。

在最新版本的 C++0x 标准中是否仍然如此? 我们需要 move实现上述模式?

最佳答案

您需要明确的 std::move在这个例子中,因为 b不是非 volatile 的名称 自动 目的。引用 12.8 [class.copy]/p31/b1:

  • 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 or catch-clause parameter) with the same cv- unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

关于operator-overloading - C++0x T operator+(const T&, T&&) 模式,还需要移动吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140607/

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