本文介绍了如果我们已经有RVO,那么移动语义的优化是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 据我所知,添加move语义的目的之一是通过调用特殊构造函数来复制临时对象来优化代码。例如,在此答案中,我们看到它可以用于优化这样的 string a = x + y stuff。因为x + y是一个右值表达式,而不是深层复制,我们只能复制指向字符串的指针和字符串的大小。但是我们知道,现代编译器支持返回值优化,因此不使用move语义,我们的代码不会调用复制构造函数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(gx) { 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; } #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 ++中执行它之后, m得到空输出。 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; }}此函数总是调用复制构造函数。如果我们的类可以移动得更快,比移动构造函数,我们将有优化。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,那么移动语义的优化是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 22:17