There's a terrific article about RVO and copy elision by Dave A at http://cpp-next.com/ If I understand this correctly a decent compiler (say VS2008) will compile this sequence using namespace std; typedef vector< string > V; V get_names( ); V sorted(V names) { sort(names); V ret; swap(ret, names); return ret; } V v = sorted( get_names( ) ); to generate zero copies - the final value of v will be the actual object generated by get_names(). Whereas this code sequence using namespace std; typedef vector< string > V; V get_names( ); V sorted(V names) { sort(names); V ret; swap(ret, names); return ret; } V tmp = get_names( ); V v = sorted( tmp ); Generates exactly one vector copy operation, at the call site of sorted(). Does that sound right? - Rob.
Robert Jones wrote:
There's a terrific article about RVO and copy elision by Dave A at
If I understand this correctly a decent compiler (say VS2008) will compile this sequence
using namespace std; typedef vector< string > V; V get_names( );
V sorted(V names) { sort(names); V ret; swap(ret, names); return ret; }
V v = sorted( get_names( ) );
to generate zero copies - the final value of v will be the actual object generated by get_names(). No, (without inlining and a compiler that really understands the semantics of swapping vectors) the final value will be the object constructed at the line "V ret;". We have the following object identities: V1: The return value of "get_names" and the parameter "names". V2: The variable "ret", the return value of "sorted", and the variable "v". Data is moved from V1 to V2 by the swap, so you have no expensive copies, but there are still two objects.
Sebastian
participants (2)
-
Robert Jones
-
Sebastian Redl