智能指针和仿函数
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){}
};