Use swap
to swap two class instances, sometimes it might throw errors.
#include <iostream>
#include <string>
using namespace std;
#include <cstring>
class Buffer {
public:
Buffer(const string& s): buffer(s) {}
string buffer;
};
template<class _Tx>
void SWAP(_Tx& a, _Tx& b) {
size_t size = sizeof(_Tx);
char buffer[size];
memcpy(buffer, &a, size);
memcpy(&a, &b, size);
memcpy(&b, buffer, size);
}
int main() {
Buffer a("This is a"), b("This is b");
swap(a,b);
cout << a.buffer << endl;
SWAP(a,b);
cout << b.buffer << endl;
return 0;
}
the std::swap
will do something like this:
template<class _Tx>
void swap(_Tx &a, _Tx &b) {
_Tx t = a;
a = b;
b = t;
}
_Tx t = a;
will call the copy constructor of _Tx
, which is Buffer::Buffer(Buffer &e)
in this case. This method try to allocate some memory, and this might cause some errors.
I try to use another method instead of std::swap
:
template<class _Tx>
void SWAP(_Tx& a, _Tx& b) {
char buffer[sizeof(_Tx)];
memcpy(buffer, &a, sizeof(_Tx));
memcpy(&a, &b, sizeof(_Tx));
memcpy(&b, buffer, sizeof(_Tx));
}
Is it a safe way ???
UPDATES
std::swap
might be safe with c++0x. This is the comparison: c99 vs. c++0x
REF what-is-the-copy-and-swap-idiom Thanks Donal Fellows's remind