[020] Turn--c++ swap function

Source: Internet
Author: User

Originally from: http://www.cnblogs.com/xloogson/p/3360847.html

1.c++ most common template Exchange function pattern: Create a temporary object , call the assignment operator of the object

1 template <classvoid swap (t& A, t& b)  2{   c10>3    4     a=5     b=C;   6 }  

You need to construct a temporary object, a copy construct, and a two-time assignment operation.

2. for int type optimization:

1 void swap (intint & __restrict b)  2{  3 a ^ = B;   4 b ^= A;   5 a ^= b;   6

You do not need to construct a temporary object, XOR.

Because the pointer is int, you can optimize 1 based on this idea:

1Template <typename t>voidSwap (T & obj1,t &obj2)2 {  3UnsignedChar* PObj1 = reinterpret_cast<unsignedChar*> (&obj1); 4UnsignedChar* PObj2 = reinterpret_cast<unsignedChar*> (&obj2); 5      for(unsignedLongx =0; X <sizeof(T); ++x)6     {  7POBJ1[X] ^=Pobj2[x]; 8POBJ2[X] ^=Pobj1[x]; 9POBJ1[X] ^=Pobj2[x]; Ten     }   One}

The process of copying construction can be saved.

3. Optimizations for built-in types: int, float, double, and even user-defined types of overloaded operators: vectors, matrices, images, etc...

1 template <classvoid swap (t& A, t& b)2{3 C7/>a = a + b; 4     b = A- b; 5     A = a- b;   6 }

You do not need to construct temporary variables. Use basic operator operators.

Some of the 4.swap's Special: std::string, std::vector each implemented the SWAP function

String

1template<class_ty,2     class_alloc>inline3     voidSwap (Vector<_ty, _alloc>& _left, Vector<_ty, _alloc>&_right)4{//swap _left and _right vectors5 _left.swap (_right); 6     }  7     voidSwap (_myt&_right)8{//Exchange contents with _right9         if( This= = &_right)Ten;//same object, do nothing One         Else if( This->_alval = =_right._alval) A{//same allocator, swap control information -  #if_has_iterator_debugging -              This-_swap_all (_right);  the  #endif/* _has_iterator_debugging */ -              This-_swap_aux (_right);  - _std Swap (_myfirst, _right._myfirst);  - _std Swap (_mylast, _right._mylast);  + _std Swap (_myend, _right._myend);  -             }   +         Else   A{//different allocator, do multiple assigns at              This-_swap_aux (_right);  -_myt _ts = * This;  -* This=_right;  -_right =_ts;  -             }   -}

Vector

1template<class_elem,2     class_traits,3     class_alloc>inline4     void__clrcall_or_cdecl swap (Basic_string<_elem, _traits, _alloc>&_left,5Basic_string<_elem, _traits, _alloc>&_right)6{//swap _left and _right strings7 _left.swap (_right); 8     }  9     void__clr_or_this_call Swap (_myt&_right)Ten{//Exchange contents with _right One         if( This= = &_right) A;//same object, do nothing -         Else if(_mybase::_alval = =_right._alval) -{//same allocator, swap control information the  #if_has_iterator_debugging -              This-_swap_all (_right);  -  #endif/* _has_iterator_debugging */ -_bxty _TBX =_BX;  +_BX = _right._bx, _RIGHT._BX =_TBX;  -Size_type _tlen =_mysize;  +_mysize = _right._mysize, _right._mysize =_tlen;  ASize_type _tres =_myres;  at_myres = _right._myres, _right._myres =_tres;  -             }   -         Else   -{//different allocator, do multiple assigns -_myt _tmp = * This;  -* This=_right;  in_right =_tmp;  -             }   to}

The second swap (right) is judged, if the same allocator is used, the control information is exchanged directly, otherwise call string::operator= for copy assignment ... Therefore, it is advisable to use the SWAP function instead of the assignment operator.

5.Copy and Swap idiom

Purpose: C + + Exception has three levels: basic, strong, no exception. Strong exception-Safe execution of overloaded assignment operators can be achieved by creating temporary objects and then exchanging them.

Loki smart pointer temporary variable with this exchange, temporary variable automatic destruction ~

1 smartptr& operator= (smartptr<t1, OP1, CP1, KP1, SP1, CNP1 >& rhs)  {      smartptr Temp (RHS);  4     Temp. Swap (*this);  5     return *this;  6}      

BOOST::SHARE_PTR,SHARE_PTR defines its own swap function.

1SHARED_PTR &operator= (shared_ptrConst& R)//never throws2 {  3This_type (R). Swap (* This); 4     return* This; 5 }  6 voidSwap (shared_ptr<t> & other)//never throws7 {  8 std::swap (px, other.px); 9 Pn.swap (OTHER.PN); Ten}

Optimization of the string::opreator= function:

The most general wording, feature: Use const string& to prevent temporary objects.

1string& String::operator=(ConstString &RHS)2 {  3     if(itsstring)4 Delete [] itsstring; 5Itslen =RHS.  Getlen (); 6Itsstring =New Char[itslen+1]; 7      for(unsigned Shorti =0; i<itslen;i++)  8Itsstring[i] =Rhs[i]; 9Itsstring[itslen] ='/0'; Ten     return* This;  One}

Optimization 1, prevent self-indirect assignment, a = b; c = b; A = C; If there is no first if judgment, when the C is assigned to a, delete the a.itsstring, the subsequent copy will be wrong. Note that it is if (THIS==&RHS), not if (*THIS==RHS) .

1string& String::operator=(ConstString &RHS)2 {  3     if( This= = &RHS)4         return* This; 5     if(itsstring)6 Delete [] itsstring; 7itslen=RHS.  Getlen (); 8Itsstring =New Char[itslen+1]; 9      for(unsigned Shorti =0; i<itslen;i++)  TenItsstring[i] =Rhs[i];  OneItsstring[itslen] ='/0';  A     return* This;  -}

Optimization 2, do not copy assignment, just exchange control information, and is strong exception security:

1String & string::operator= (StringConst&RHS)2 {  3     if( This! = &RHS)4String (RHS). Swap (* This);//Copy-constructor and non-throwing swap5     //Old Resources is released with the destruction of the temporary above6     return* This; 7}

Optimization 3, the most primitive way of transmitting parameters to avoid temporary object creation:

1 operator // The pass-by-value parameter serves as a temporary   2 {  3    s.swap (*this//  non-throwing swap  4     return *this;   5 }// old Resources released when destructor of S is called.  

[020] Turn--c++ swap function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.