C++:智能指针和仿函数

智能指针和仿函数

1. pointer-like classes,关于智能指针

1.1. 基础知识

  • 下方代码中定义的类实现了指针的功能,也称为智能指针
template<class T>
class shared_ptr
{
public:
    T& operator*() const       //写法一
    {  return *px;  }
    
    T* operator->() const     //写法二
    {  return px;  }
    
    shared_ptr(T* p):px(p){ }
private:
    T* px;
    long* pn;
}

在这里插入图片描述

应用:

struct Foo
{
    ...
	void method(void){.....}
}

int main()
{
    shared_ptr<Foo> sp(new Foo);
    
    Foo f(*sp);
    
    sp->method();   //通过shared_ptr中对->操作符的重写,变为px->method();
}

1.2. 迭代器

  • 迭代器就是要代表容器里的一个元素,指向该元素。因此迭代器也是一种智能指针。
template<class T,class Ref,class Ptr>
struct _list_iterator{
	typedef Ptr pointer;
	typedef Ref reference;
	typedef _list_node<T>* link_type; //指向一个节点
	link_type node;      //链表的指针
		
	reference operator*() const{ return (*node).data; }    //取到节点数据
	
	pointer operator->() const { return &(operator*());}
};
list<Foo>::iterator ite;

*ite;    //获得一个Foo object
ite->method();   // 调用 Foo::method(),
				 // 相当于 (*ite).method();   
				 // 相当于 (&(*ite))->method();

2. function-like classes,所谓仿函数

对于一个函数而言,函数名以及调用函数的方式——( )是必不可少的

template <class T>
struct identity{
    const T& 
    operator () (const T& x) const { return x; }
};

template <class Pair>
struct select1st{
    const typename Pair::first_type&
    operator()(const Pair& x)const{ return x.first;}
};

template <class Pair>
struct select2nd{
    const typename Pair::second_type&
    operator()(const Pair& x)const{ return x.second;}
};

template <class T1,class T2>
struct pair{
    T1 first;
    T2 second;
    pair() :first(T1()),second(T2()){}
    pair(const T1& a,const T2& b):first(a),second(b){}
};

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值