Making swap faster, easier to use and exception-safe

前端 未结 5 1373
忘了有多久
忘了有多久 2020-12-15 22:49

I could not sleep last night and started thinking about std::swap. Here is the familiar C++98 version:

template 
void swap(T&a         


        
5条回答
  •  攒了一身酷
    2020-12-15 23:09

    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

提交回复
热议问题