[020]转--C++ swap函数

原文来自:http://www.cnblogs.com/xloogson/p/3360847.html

1.C++最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符

1 template <class T> void swap ( T& a, T& b )
2 {
3     T c(a);
4     a=b;
5     b=c;
6 }  

需要构建临时对象,一个拷贝构造,两次赋值操作。

2.针对int型优化:

1 void swap(int & __restrict a, int & __restrict b)
2 {
3   a ^= b;
4   b ^= a;
5   a ^= b;
6 } 

无需构造临时对象,异或。

因为指针是int,所以基于这个思路可以优化1:

 1 template <typename T> void Swap(T & obj1,T & obj2)
 2 {
 3     unsigned char * pObj1 = reinterpret_cast<unsigned char *>(&obj1);
 4     unsigned char * pObj2 = reinterpret_cast<unsigned char *>(&obj2);
 5     for (unsigned long x = 0; x < sizeof(T); ++x)
 6     {
 7         pObj1[x] ^= pObj2[x];
 8         pObj2[x] ^= pObj1[x];
 9         pObj1[x] ^= pObj2[x];
10     }
11 }

可以省下拷贝构造的过程。

3.针对内建类型的优化:  int, float, double 等,甚至重载运算符的用户自定义类型:向量,矩阵,图像等。。。

1 template <class T> void swap ( T& a, T& b )
2 {
3     a = a + b;
4     b = a - b;
5     a = a - b;
6 }

// 无需构造临时变量。使用基本运算操作符。

4.swap的一些特化:std::string, std::vector各自实现了swap函数

string:

 1 template<class _Ty,
 2     class _Alloc> inline
 3     void swap(vector<_Ty, _Alloc>& _Left, vector<_Ty, _Alloc>& _Right)
 4     {   // swap _Left and _Right vectors
 5     _Left.swap(_Right);
 6     }
 7     void swap(_Myt& _Right)
 8         {   // exchange contents with _Right
 9         if (this == &_Right)
10             ;   // same object, do nothing
11         else if (this->_Alval == _Right._Alval)
12             {   // same allocator, swap control information
13  #if _HAS_ITERATOR_DEBUGGING
14             this->_Swap_all(_Right);
15  #endif /* _HAS_ITERATOR_DEBUGGING */
16             this->_Swap_aux(_Right);
17             _STD swap(_Myfirst, _Right._Myfirst);
18             _STD swap(_Mylast, _Right._Mylast);
19             _STD swap(_Myend, _Right._Myend);
20             }
21         else
22             {   // different allocator, do multiple assigns
23             this->_Swap_aux(_Right);
24             _Myt _Ts = *this;
25             *this = _Right;
26             _Right = _Ts;
27             }
28         }  

vector:

 1 template<class _Elem,
 2     class _Traits,
 3     class _Alloc> inline
 4     void __CLRCALL_OR_CDECL swap(basic_string<_Elem, _Traits, _Alloc>& _Left,
 5         basic_string<_Elem, _Traits, _Alloc>& _Right)
 6     {   // swap _Left and _Right strings
 7     _Left.swap(_Right);
 8     }
 9     void __CLR_OR_THIS_CALL swap(_Myt& _Right)
10         {   // exchange contents with _Right
11         if (this == &_Right)
12             ;   // same object, do nothing
13         else if (_Mybase::_Alval == _Right._Alval)
14             {   // same allocator, swap control information
15  #if _HAS_ITERATOR_DEBUGGING
16             this->_Swap_all(_Right);
17  #endif /* _HAS_ITERATOR_DEBUGGING */
18             _Bxty _Tbx = _Bx;
19             _Bx = _Right._Bx, _Right._Bx = _Tbx;
20             size_type _Tlen = _Mysize;
21             _Mysize = _Right._Mysize, _Right._Mysize = _Tlen;
22             size_type _Tres = _Myres;
23             _Myres = _Right._Myres, _Right._Myres = _Tres;
24             }
25         else
26             {   // different allocator, do multiple assigns
27             _Myt _Tmp = *this;
28             *this = _Right;
29             _Right = _Tmp;
30             }
31         }  

第二个swap(Right)进行判断,如果使用了相同的分配器,则直接交换控制信息,否则调用string::operator=进行拷贝赋值。。。所以建议优先使用swap函数,而不是赋值操作符。

5.Copy and  Swap idiom

目的:C++异常有三个级别:基本,强,没有异常。通过创建临时对象然后交换,能够实现重载赋值操作符的强异常安全的执行。

Loki中智能指针 临时变量跟this交换,临时变量自动销毁~

1 SmartPtr& operator=(SmartPtr<T1, OP1, CP1, KP1, SP1, CNP1 >& rhs)
2 {
3     SmartPtr temp(rhs);
4     temp.Swap(*this);
5     return *this;
6 }  

boost::share_ptr,share_ptr定义了自己的swap函数。

 1 shared_ptr & operator=( shared_ptr const & r ) // never throws
 2 {
 3     this_type(r).swap(*this);
 4     return *this;
 5 }
 6 void swap(shared_ptr<T> & other) // never throws
 7 {
 8     std::swap(px, other.px);
 9     pn.swap(other.pn);
10 }  

String::opreator=函数的优化:

最一般的写法,特点:使用const string& 传参防止临时对象。

 1 String& String::operator =(const String & rhs)
 2 {
 3     if (itsString)
 4         delete [] itsString;
 5     itsLen = rhs.GetLen();
 6     itsString = new char[itsLen+1];
 7     for (unsigned short i = 0;i<itsLen;i++)
 8         itsString[i] = rhs[i];
 9     itsString[itsLen] = ‘/0‘;
10     return *this;
11 }  

优化1,防止自我间接赋值,a = b; c = b; a = c; 如果没有第一个if判断,当把c赋给a的时候,删除了a.itsString,后面的拷贝就会出错。注意是if(this==&rhs), 而不是if(*this==rhs) .

 1 String& String::operator =(const String & rhs)
 2 {
 3     if (this == &rhs)
 4         return *this;
 5     if (itsString)
 6         delete [] itsString;
 7     itsLen=rhs.GetLen();
 8     itsString = new char[itsLen+1];
 9     for (unsigned short i = 0;i<itsLen;i++)
10         itsString[i] = rhs[i];
11     itsString[itsLen] = ‘/0‘;
12     return *this;
13 }  

优化2,不进行拷贝赋值,只是交换控制信息,而且是强异常安全:

1 String & String::operator = (String const &rhs)
2 {
3     if (this != &rhs)
4         String(rhs).swap (*this); // Copy-constructor and non-throwing swap
5     // Old resources are released with the destruction of the temporary above
6     return *this;
7 }  

优化3,以最原始的传值方式传参,避免临时对象创建:

1 String & operator = (String s) // 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.  
时间: 2024-08-29 18:28:53

[020]转--C++ swap函数的相关文章

《Effective C 》资源管理:条款25--考虑写出一个不抛出异常的swap函数

条款25考虑写出一个不抛出异常的swap函数 条款25:考虑写出一个不抛出异常的swap函数 swap是STL中的标准函数,用于交换两个对象的数值.后来swap成为异常安全编程(exception-safe programming,条款29)的脊柱,也是实现自我赋值(条款11)的一个常见机制.swap的实现如下: namespace std{ template<typename T> void swap(T& a, T& b) { T temp(a); a=b; b=temp;

swap函数的例子

13.31为你的HasPtr类定义一个<运算符,并定义一个HasPtr的vector为这个vector添加一些元素,并对它执行sort.注意何时会调用swap. #include<iostream> #include<string> #include<new> #include<vector> #include<algorithm> using namespace std; class HasPtr { friend void swap(H

条款25:考虑写出一个不抛异常的swap函数

条款25:考虑写出一个不抛异常的swap函数 swap函数在C++中是一个非常重要的函数,但实现也非常复杂. 看一个缺省的std::swap函数的实现 namespace std { template<typename T> void swap( T& a , T& b) { T temp(a); a = b; b = temp } } ①内置类型的调用 int a = 2; int b =3; std::swap(a, b); cout<<"a:&quo

作业二、comp和swap函数

一.swap函数的代码及运行情况 1.代码 1 #include<stdio.h> 2 int main() 3 { 4 void swap(int *m,int *n); 5 int a,b; 6 int *p1,*p2; 7 scanf("%d,%d",&a,&b); 8 p1=&a; 9 p2=&b; 10 swap(p1,p2); 11 printf("%d,%d\n",*p1,*p2); 12 return 0;

关于swap函数传值的问题

#include <stdio.h> void swap(int * p3,int * p4); int main() {  int a = 9;  int b = 8;  int * p1 = &a;  int * p2 = &b;    printf("%x %x\n",p1,p2);  swap(p1,p2);    printf("%d %d\n",a,b);  printf("%d %d\n",*p1,*p2

c/c++和java实现swap函数的不同处

首先我们来看一下在c/c++中实现的swap函数 void swap ( int & a, int & b) { int Temp; temp = a; a = b; b = temp; } 那么在java中是否还能这样呢,很显然java中没有地址引用符号了. 首先我们来看下c/c++和java的区别. 本质区别 C/C++中swap功能的本质:通过传递变量地址(指针或引用)来交换变量地址中的值. Java标榜其中对C/C++一个很大的改进就是:Java对程序员屏蔽了变量地址的概念,减少指

C语言形参与实参的概念及swap函数

形式参数(formal argument)和实际参数(actual argument)是什么? void function(int n); //n为形式参数 int main { int times=5; function(times); //times为实际参数 } void function(int n) { for(int i=0;i<n;i++) printf("hello\n"); } 在声明一个参数时就创建了一个叫形式参数的变量,在上面的例子中形式参数是叫做n的变量.

Effective C++ Item 25 考虑写出一个不抛异常的swap函数

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie 经验:当std::swap对你的类型效率不高时,提供一个swap成员函数,并确定这个函数不抛出异常 示例: stl里的swap算法 namespace std{ template<typename T> void swap(T &a, T &b){ T temp(a); a = b; b = temp; } } //"pimpl手法"(pointer

Effective C++ 条款25 考虑写出一个不抛出异常的swap函数

1. swap是STL的一部分,后来成为异常安全性编程(exception-safe programming)(见条款29)的一个重要脊柱,标准库的swap函数模板定义类似以下: namespace std{ template<typename T> swap(T& lhs,T& rhs){ T temp(lhs); lhs=rhs; rhs=temp; } } 只要T类型支持拷贝构造以及拷贝赋值,标准库swap函数就会调用T的拷贝构造函数和拷贝构造操作符完成值的转换,但对于某