在构建复合对象时消除不必要的副本 [英] Eliminating unnecessary copies when building composite objects

查看:124
本文介绍了在构建复合对象时消除不必要的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想想开发一些命名的参数代码,但它让我想到一些代码,如下所示:

  include< utility> 

int main()
{
使用std :: make_pair;
auto x = make_pair(1,make_pair(2,make_pair(3,make_pair(4,5))));
}



现在,一个幼稚的实现这将make_pair ,然后将结果复制到make_pair(3,...)的第二个元素,然后将其复制到make_pair(2,...)的第二个元素等。



这将导致O(n ^ 2)性能不幸,有很多不必要的副本。



理想情况下, make_pair(4,5) 实现它将位于 x 的最后一个位置,并在该位置构建自己。



进一步:

  #include< utility> 

int main()
{
使用std :: make_pair;
auto&&& x1 = make_pair(3,make_pair(4,5));
auto x2 = make_pair(1,make_pair(2,std :: move(x1)));
}

我想避免这样的代码中的副本。 p>

这个优化是如此明显,我应该假定编译器执行它,还是有另一种方法我应该编码这避免副本?

解决方案

[N] RVO在这种情况下有帮助。基本上发生的是,一个组合对象被分配,并且每个函数的返回值直接进入将保存结果的对象。



如果你打算做很多这一切(特别是在C ++ 11),几乎肯定更干净,更简单,更直接使用元组,所以你的:

  auto x = make_pair(1,make_pair(2,make_pair(3,make_pair(4,5)))); 

会最终显示为:

  auto x = make_tuple(1,2,3,4,5); 

这可能不会影响生成的代码太多,但(至少IMO)阅读。


I was thinking of developing some named parameter code, but it got me thinking of some code like the following:

#include <utility>

int main() 
{
  using std::make_pair;
  auto x = make_pair(1, make_pair(2, make_pair(3, make_pair(4,5))));
}

Now, a naive implementation of this would do "make_pair(4,5)" first, then copy the result into the second element of "make_pair(3, ...)", and then copy that into the second element of "make_pair(2, ...)" etc.

This would result in O(n^2) performance unfortunately, with a lot of unnecessary copies. I can't see how (named) return value optimization helps here either.

Ideally, make_pair(4,5) realizes it's going to be in the last spot of x, and constructs itself in that place.

Taking this further:

#include <utility>

int main() 
{
  using std::make_pair;
  auto&& x1 = make_pair(3, make_pair(4,5));
  auto x2 = make_pair(1, make_pair(2, std::move(x1)));
}

I'd like to avoid the copies in code like this also.

Is this optimization so obvious that I should assume compilers perform it or is there another way I should be coding this to avoid the copies?

解决方案

[N]RVO does help in cases like this. Basically what happens is that one composite object gets allocated, and the "return value" from each of the functions ends up going directly into the object that will hold the result.

If you're going to do much of this (especially in C++11), it's almost certainly cleaner, simpler and more direct to use a tuple instead, so your:

auto x = make_pair(1, make_pair(2, make_pair(3, make_pair(4,5))));

would end up like:

auto x = make_tuple(1, 2, 3, 4, 5);

This probably won't affect the generated code much, but (at least IMO) it's a lot easier to read.

这篇关于在构建复合对象时消除不必要的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆