Which version of swap would be faster, the macro or the function: http://ideone.com/lWU9r ?
Some hits on google indicate that macro would be faster. I am sorry i dont know for sure, but would like to know.
Most likely the macro, because: -No dynamic allocation. That alone will take as long as the swap in most cases :P -No branching It's also more compact and readable, and avoids void pointers. Void pointers are evil because they have no type - there is no way to guarantee, for example in this case, that the parameter passed in as size is actually the size of the type being swapped. I could call this with a wrong size of 1MByte and quite likely either crash the application or cause a nasty bug that only manifests in a completely different area of the code later on. There are specific cases where void pointers come in handy, but it's usually worth thinking twice before using them. Larry the type safe monkey says, be type safe! :P
what if instead of using a swap macro, I implement a swap function for each different type?
You could do that, but that has the obvious drawbacks (of having to duplicate lots of code). An alternative is (and yes, I know i sound like a broken record) to use C++, write a swap function template, and let the compiler generate a new version for each needed type for you ;)
I think C++ has std::swap() anyway
Yeah, but where's the fun in that?
Also, there are cases where you can't rely on the STL being available or a very good idea. Playstation 3 SPU code is one example, and the same goes for most specialized processors on embedded systems. Of course, for 99.9% of general purpose computer cases you are absolutely right, use std::swap ;)
templates sound like the most useful feature of C++.
It's one of them. There's the whole OO thing of course, which really shows its advantage when you start writing larger code bases. I really wouldn't want to maintain a >1M line code base without OOD ;) There are also other features which can make your code more explicit and reliable, such as C++ casts. With the latest addition to the standard (C++11) there are a lot of other nifty things like initializer list objects, type inference, range based loops, thread local storage model, compile time asserts, etc. etc.
Join our real-time social learning platform and learn together with your friends!