Sunday, December 15, 2013

C++11 move semantics are amazing

Right now I’m testing Visual C++ 2013, which implements some interesting innovations from C++11 specification. I started taking a look at some of them, and the move semantics instantly caught my attention because they solve a problem I was just facing. I implemented a smart pointer class so that I could return a string object from a function – my own String class, I don’t use STL –, and it was something like this:
Ptr<String> Function() {
	Ptr<String> ret = new String();
	return ret;
}
This worked perfectly fine. What bugged me was that two more allocations are needed on this approach: the internal smart pointer instance counter, and the pointer itself. These two allocations, of course, are summed up to the internal String array allocation, so I ended up with three memory allocations for a trivial string return. That sounded too much to my optimization paranoia.

Now, with the new C++11 move semantics, when we write the constructor and the assignment operator for a class, we write specific code to use when receiving a temporary object, which will be destroyed right after the operation completes – it means we can do whathever we want with this temporary object, no one will bother. After implementing the move semantics on my String class, and on the underneath Array class which powers it, I could rewrite the above function like this:
String Function() {
	String ret;
	return ret;
}
My return object is allocated on the stack, not heap-allocated, so we have saved one allocation. And since I’m not returning a pointer – but rather returning the object my value – we don’t need the smart pointer anymore, so we saved another allocation. In the end, we shrinked down from three to only one single allocation, the internal string array itself. With the move semantics implemented, the internal string array just flies from an object into another, without cloning the whole array.

Right now I feel I won’t even need my smart pointer class anymore, as I’ll refactor all my classes to take advantage of the move semantics: the implications are huge. This will result in a general optimization, saving several memory allocations all around. And that’s amazing. All right, call me a C++11 guy now, it has just got me, I’ve been converted.

No comments: