The reference on std::swap disclaims that it uses a copy constructor and two assignment operators which may not be the most efficient way to swap two containers.
I was thinking about it and came up with this:
1 2 3 4 5 6 7
template <class T>
void swap(T& a, T& b)
a ^= b;
b ^= a;
a ^= b;
It works for primitive types, but to work on classes the ^= operator needs to be overloaded. Is there a way to cast a complex object to raw binary data so that I can still perform bit-wise operations on it?
I know this sounds like a REALLY bad idea, but the more I think about it, the better it sounds to me. Example, a class containing an entire 15MB wave file would really just have the data in an array, aka a pointer. Using a bitwise XOR would swap the pointer, which swaps the data reference without the need to physically move that data. Even if that data is in a std::vector, at a very low level it's still all just pointers to data (sizeof doesn't change depending on the operations I perform).
The only part that may be funky would be the function/instruction pointers that are internal to the class. I'm not entirely sure how those would transfer over.
3. For classes, swap() is a fundamental member function, most well-designed C++ classes provide it along with copy/move constructors (see std::vector for example). Before moves became part of the language, they were implemented through swaps.
(edit, dropped the directives in the second paste)
That's confusing, the only difference between those two codes are the three extra xorl instructions that I assume represent the three ^= that I put in there. I assume the rest is the function call stuff. So I'm confused on what the std::swap is even doing there.
Forgive my ignorance of ASM, but could it be hidden in that .cfg_startproc?
This is what it says according to my understanding:
??? -- Guessing this is linking to another .obj
??? -- that contains the std::swap instructions
check out a to eax
check out b to edx
check in b back to the origin
check in a back to the origin
But thanks for the replies. I know about the STL swap functions, but I'm still not quite sure why the xor hack won't work.
Anyways, it was just an academic question (I don't plan on implementing this in a project).
> a class containing an entire 15MB wave file would really just have the data in an array, aka a pointer.
> Using a bitwise XOR would swap the pointer, which swaps the data reference
> without the need to physically move that data.
Define a noexcept destructor, noexcept move constructor and a noexcept move assignment operator and std::swap() would do the same thing.