RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Move Semantics: Make Your Next Move -2 : Page 2

Moving versus Copying
Moving, as opposed to copying, means that a target object pilfers (get used to this technical term!) the source object's resources, instead of reduplicating or sharing them. By contrast, copying means that the target and the source objects end up having two identical, though independent, copies of the resource. Here's a trivial example of copying:
const char msg[]="hi";
char s[3]
strcpy(s, msg);
After the execution of the strcpy() call, you have two strings: msg and s, that contain the same values in two different memory locations. The copy operation didn't modify the source.

Move-Based Swapping
In many cases, copying is the right operation to do; you really want to copy the state of the source object to the target object without altering the source. However, there are programming tasks that can be implemented without such reduplication of resources. Take, for example, the concept of swapping, that is, the target and the source exchange their states. A naive swap implementation would create redundant copies:

template <class T> 
void swap(T t1, T t2)
 T temp=t1; //copy
 t1=t2; //copy
 t2=temp; //copy
When the swap() arguments are integers or Boolean values, this trivial implementation is efficient. However, suppose you want to swap two strings:
string s1="hello";
string s2="world";

Swapping s1 and s2 by means of creating a temporary string object, copying one of the strings to it, and then copying two more strings is unnecessarily slow:

void swapstrings(string s1, string s2)
 string temp=s1; //copy
 s1=s2; //copy
 s2=temp; //copy

Instead of messing with memory allocations and linear copying of characters, there's a simpler and more efficient technique: moving the two strings. In this context, moving means exchanging the internal pointers and sizes of the string objects, as you can see in this pseudo-code:

void swapstr(string &a, string &b)
 size_t tempsz=a.size();
 const char *p= a.data();
//a pilfers b's resources 
 a.data=b.data();//pointer assignment,not buffer copying
//b pilfers a's resources

This version costs six simple assignments of word-sized datatypes. By contrast, a copy-based swap is a linear operation, and its execution time depends on the length of the two strings. The longer their cumulative length is, the slower the operation is.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date