I could not sleep last night and started thinking about std::swap
. Here is the familiar C++98 version:
template
void swap(T&a
your swap
version will cause havoc if someone uses it with polymorphic types.
consider:
Base *b_ptr = new Base(); // Base and Derived contain definitions
Base *d_ptr = new Derived(); // of a virtual function called vfunc()
yourmemcpyswap( *b_ptr, *d_ptr );
b_ptr->vfunc(); //now calls Derived::vfunc, while it should call Base::vfunc
d_ptr->vfunc(); //now calls Base::vfunc while it should call Derived::vfunc
//...
this is wrong, because now b contains the vtable of the Derived
type, so Derived::vfunc
is invoked on a object which isnt of type Derived
.
The normal std::swap
only swaps the data members of Base
, so this is OK with std::swap