RVO会发生在返回std :: pair吗? [英] Will RVO happen when returning std::pair?

查看:242
本文介绍了RVO会发生在返回std :: pair吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数需要向调用者返回两个值。



选项1:

 对< U,V> myfunc()
{
...
return make_pair(getU(),getV());
}

pair< U,V> mypair = myfunc();

选项1.1:

  // Same defn 
U u; V v;
tie(u,v)= myfunc();

选项2:

  void myfunc(U& u,V& v)
{
u = getU(); v = getV();
}

U u; V v;
myfunc(u,v);

我知道Option2,没有副本/移动,但它看起来很丑陋。在Option1,1.1中会有任何副本/移动吗?假设U和V是支持复制/移动操作的巨大对象。



问题:对于任何RVO / NRVO优化,按照标准理论上是否可能?如果是,是否有gcc或任何其他编译器实现?

解决方案


当返回 std :: pair ?





$ b

不是。






C ++ 11标准: 12.8 / 31:


当满足特定条件时,允许实现省略类的复制/对象,即使该对象的复制/移动构造函数和/或析构函数有副作用。


复制elision不是保证的功能。它是一个优化编译器允许 。没有什么特别的w.r.t std :: pair 。如果编译器足够好以检测优化机会,它将这样做。所以你的问题是编译器的具体,但同样的规则适用于 std :: pair 任何其他类。


A function needs to return two values to the caller. What is the best way to implement?

Option 1:

pair<U,V> myfunc()
{
...
return make_pair(getU(),getV());
}

pair<U,V> mypair = myfunc();

Option 1.1:

// Same defn
U u; V v;
tie(u,v) = myfunc();

Option 2:

void myfunc(U& u , V& v)
{
u = getU(); v= getV();
}

U u; V v;
myfunc(u,v);

I know with Option2, there are no copies/moves but it looks ugly. Will there be any copies/moves occur in Option1, 1.1? Lets assume U and V are huge objects supporting both copy/move operations.

Q: Is it theoretically possible for any RVO/NRVO optimizations as per the standard? If yes, has gcc or any other compiler implemented yet?

解决方案

Will RVO happen when returning std::pair?

Yes it can.

Is it guaranteed to happen?

No it is not.


C++11 standard: Section 12.8/31:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.

Copy elision is not a guaranteed feature. It is an optimization compilers are allowed to perform whenever they can. There is nothing special w.r.t std::pair. If a compiler is good enough to detect an optimization opportunity it will do so. So your question is compiler specific but yes same rule applies to std::pair as to any other class.

这篇关于RVO会发生在返回std :: pair吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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