缺失一元 std::copy 的最佳实现
C++11 引入了语义来避免不必要的对象复制,并引入了 std::move 来在发生复制时应用这些语义。然而,现在也有一些情况需要副本,但不是默认的。
例如,考虑一下这个简单的reverse
实现。由于基于范围的 for
使用完美转发,因此对循环内的容器进行修改会导致损坏。
auto out_iter = container.rbegin();
for ( auto value : container ) {
* out_iter ++ = value;
}
目标是使用
for ( auto value : copy( container ) ) {
“看起来很简单......接受任何参数,获取基础类型并返回临时副本”来解决此问题。
C++11 introduces semantics to avoid unnecessarily copying objects, and std::move
to apply those semantics when otherwise a copy would occur. However, there are now also some cases where a copy is required, but not the default.
Consider this naive implementation of reverse
, for example. Because range-based for
uses perfect forwarding, modification to the container within the loop amounts to corruption.
auto out_iter = container.rbegin();
for ( auto value : container ) {
* out_iter ++ = value;
}
The goal is to fix this using
for ( auto value : copy( container ) ) {
It seems simple enough… accept any argument, get the underlying type and return a temporary copy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在计算的返回类型通常称为
typename std::decay::type
。除此之外,在正文中使用std::forward
可以获得完美转发的全部好处:The return type you're computing is better known as
typename std::decay<T>::type
. Other than that, usestd::forward
in the body to reap the full benefits of perfect forwarding: