返回一对对象
以下是反模式:
auto f() {
std::vector<int> v(100000);
return std::move(v); // no need to use std::move thanks to RVO (return value optimization)
}
使用 std::move
甚至可能产生最糟糕的代码(请参阅此处< /a>)
但是,遇到以下情况我该怎么办:
auto f() {
std::vector<int> v0(100000);
std::vector<int> v1(100000);
return std::make_pair(std::move(v0),std::move(v1)); // is the move needed?
}
The following is an anti-pattern:
auto f() {
std::vector<int> v(100000);
return std::move(v); // no need to use std::move thanks to RVO (return value optimization)
}
Using a std::move
can even produce worst code (see here)
However, what should I do in the following situation:
auto f() {
std::vector<int> v0(100000);
std::vector<int> v1(100000);
return std::make_pair(std::move(v0),std::move(v1)); // is the move needed?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于第二个代码段,
return
返回std::make_pair()
函数的结果。这是一个 RValue。然而,OP的问题可能归结为是否(或为什么不)命名返回值优化std::pair 返回时,a> 仍然适用于
v0
/v1
。因此,我们忽略了
v0
/v1
不再是return
的主题,而是成为std::make_pair() 的参数
。因此,v0
/v1
是 LValues –std::move(v0), std::move(v1)
必须应用于如果需要移动语义,请将它们转换为 RValue。coliru 演示:
输出:
For the second snippet,
return
returns the result of thestd::make_pair()
function. That's an RValue.However, the OP's question probably condenses to whether (or why not) Named Return Value Optimization still applies to
v0
/v1
when returned as astd::pair
.Thereby, it's overlooked that
v0
/v1
aren't subject ofreturn
anymore, but become arguments ofstd::make_pair()
. As such,v0
/v1
are LValues –std::move(v0), std::move(v1)
have to be applied to turn them into RValues if move-semantic is intended.Demo on coliru:
Output:
是的,需要进行此移动以避免在后一种情况下进行复制。
然而,这样会更好:
Yes, the move is needed to avoid copy in the latter case.
However, this would be even better: