写一个高效的swap函数

一、前提

缺省版本的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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值