Generic C++ object/structure swap
I developed a simple object swap template. I simply do a binary swap of the class/structure contents. Yet I know that the developers of the STL libraries do not implement swaps in this way. Their implementation will make copies (via a copy constructor) and then use an assignment operator - "operator=()". The reason I want to do swaps in this manner is because of the obvious efficiencies. For instance, if I wanted to swap two branches of two very large tree structures, the copy and assignment operations become prohibative.
My question is in what instances does the code below NOT work?
template <typename _Ty>
void ObjectSwap(_Ty &obj1, _Ty &obj2)
{
// Don't swap on the same object
if (&obj1 != &obj2)
{
char tmp[sizeof(_Ty)]; // create a memory buffer
size_t sz = sizeof(_Ty);
memcpy((void *) tmp, (const void *) &obj1, sz);
memcpy((void *) &obj1, (const void *) &obj2, sz);
memcpy((void *) &obj2, (const void *) tmp, sz);
}
}
Re: Generic C++ object/structure swap
Quote:
Originally posted by scottk@intellig
I developed a simple object swap template. I simply do a binary swap of the class/structure contents. Yet I know that the developers of the STL libraries do not implement swaps in this way. Their implementation will make copies (via a copy constructor) and then use an assignment operator - "operator=()". The reason I want to do swaps in this manner is because of the obvious efficiencies.
This is not guranteed to work for non-POD types.
What is a POD type? A POD type is a basic data type (int, char, double, float, etc.), a structure or class that contains these types, or arrays of these types -- basically anything that 'C' can handle as far as data types go. If you are swapping a class or struct that contains member functions, destructors, or contain members that are not POD themselves, your swap will cause undefined behavior and your program to be unstable.
Your method will work if you can guarantee that the types you are swapping are POD (Plain Old Data) types. Then you can do a specialization for std::swap (which is the proper way to do what you want -- you don't have to write another completely different function). This allows the STL framework to call your "swap" instead of the default.
There is a reason why the default std::swap does what you observe. The reason is that to copy any object correctly and without invoking undefined behavior, you must call the objects assignment or copy constructor.
Regards,
Paul McKenzie