写一个高效的swap函数

来源:互联网 发布:php新手入门教程 编辑:程序博客网 时间:2024/04/28 19:12

一、前提

缺省版本的swap函数的实现方式是通过构造三个对象以及其内部的成员变量,如果某个对象很庞大,这样复制三次的效率是非常低的,因此需要写一个自定义的swap函数,但因为其调用方式跟一般的调用方式有所区别比如如下代码

class widget
 {
  public:
   widget(int x)
   {
    p =new int;
    *p=x;
   }
   void swap(widget& other )
   {
    using std::swap; //必须加,否则无法调用系统的swap函数中
    swap(p,other.p);
   }
   void print()
   {
    printf("%d\n",*p);
   }
  private:
   int *p;
 };

建立两个对象并调用

widget a(1),b(2);

a.swap(b);

这样的写法对用户来说实在太不友好了,于是可以用以下方法,在类的下面写一个非成员函数

void swap(widget& a,widget& b)
 {
  a.swap(b);
 }

然后在main函数中这样写

widget a(1),b(2);

swap(a,b);

 

也就是这些代码全部放在同一个头文件中

一般情况下再加个命名空间会比较安全,如下全部代码所示

namespace tt
{

 class widget
 {
  public:
   widget(int x)
   {
    p =new int;
    *p=x;
   }
   void swap(widget& other )
   {
    using std::swap;
    swap(p,other.p);
   }
   void print()
   {
    printf("%d\n",*p);
   }
  private:
   int *p;
 };

 void swap(widget& a,widget& b)
 {
  a.swap(b);
 }
}

 

二、类是模板类

namespace tt
{

template<typename T>

 class widget
 {
  public:
   widget(int x)
   {
    p =new int;
    *p=x;
   }
   void swap(widget& other )
   {
    using std::swap;
    swap(p,other.p);
   }
   void print()
   {
    printf("%d\n",*p);
   }
  private:
   T *p;
 };

template<typename T>

 void swap(widget<T>& a,widget<T>& b)
 {
  a.swap(b);
 }
}

 

三、请记住

1.提供一个高效的swap函数

2.在你的class或template所在的命名空间内提供一个非成员函数 swap,并令它调用上述的swap函数

 

 

 

0 0
原创粉丝点击