问题描述
据我所知,添加移动语义的目的之一是通过调用特殊构造函数来复制临时"对象来优化代码.例如,在这个答案中,我们看到它可以用来优化这样的 string a = x + y
东西.因为 x+y 是一个右值表达式,所以我们可以只复制指向字符串的指针和字符串的大小,而不是深度复制.但正如我们所知,现代编译器支持返回值优化,因此如果不使用移动语义,我们的代码将不会完全调用复制构造函数.
As far as I understand one of the purposes of adding move semantics is to optimize code by calling special constructor for copying "temporary" objects. For example, in this answer we see that it can be used to optimize such string a = x + y
stuff. Because x+y is an rvalue expression, instead of deep copying we can copy only the pointer to the string and the size of the string. But as we know, modern compilers support return value optimization, so without using move semantics our code will not call the copy constructor at all.
为了证明这一点,我写了这段代码:
To prove it I write this code:
#include <iostream>
struct stuff
{
int x;
stuff(int x_):x(x_){}
stuff(const stuff & g):x(g.x)
{
std::cout<<"copy"<<std::endl;
}
};
stuff operator+(const stuff& lhs,const stuff& rhs)
{
stuff g(lhs.x+rhs.x);
return g;
}
int main()
{
stuff a(5),b(7);
stuff c = a+b;
}
在 VC++2010 和 g++ 中以优化模式执行后,我得到了空输出.
And after executing it in VC++2010 and g++ in optimize mode I'm getting empty output.
这是一种什么样的优化,如果没有它我的代码仍然运行得更快?你能解释一下我的理解错误吗?
What kind of optimization is it, if without it my code still works faster? Could you explain what I'm understanding wrong?
推荐答案
经过一番挖掘,我在Stroustrup 的常见问题解答 .
After some digging I find this excellent example of optimization with rvalue references inStroustrup's FAQ .
是的,交换函数:
template<class T>
void swap(T& a, T& b) // "perfect swap" (almost)
{
T tmp = move(a); // could invalidate a
a = move(b); // could invalidate b
b = move(tmp); // could invalidate tmp
}
这将为任何类型的类型生成优化代码(假设它具有移动构造函数).
This will generate optimized code for any kind of types (assuming, that it have move constructor).
RVO 也不能优化这样的东西(至少在我的编译器上):
Also RVO can't optimize something like this(at least on my compiler):
stuff func(const stuff& st)
{
if(st.x>0)
{
stuff ret(2*st.x);
return ret;
}
else
{
stuff ret2(-2*st.x);
return ret2;
}
}
这个函数总是调用复制构造函数(用VC++检查).如果我们的类可以移动得更快,那么与移动构造函数相比,我们将得到优化.
This function always calls copy constructor (checked with VC++). And if our class can be moved faster, than with move constructor we will have optimization.
这篇关于如果我们已经有了 RVO,移动语义会提供什么优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!