仿函数&share_ptr(指针类)

  • share_ptr
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    template<class T>
    class share_ptr{
    T& operator*() const{
    return *px;
    }

    T* operator->() const{
    return px;
    }

    share_ptr(T* p):px(p){}

    private:
    T* px;
    long* pn;
    }

    智能指针

    share_ptr

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    template<class T>
    class share_ptr{
    T& operator*() const{
    return *px;
    }

    T* operator->() const{
    return px;
    }

    share_ptr(T* p):px(p){}

    private:
    T* px;
    long* pn;
    }

    struct Foo
    {
    void method(void){}
    }

    shared_ptr<Foo> sp(new Foo());
    Foo f(*sp);
    sp->method();//->不会被消耗掉

    迭代器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    template<class T>
    struct __list_node{
    void* prev;
    void* next;
    T data;
    };

    template<class T,class Ref,class Ptr>
    struct __list_iterator{
    typedef __list_iterator<T,Ref,Ptr> self;
    typedef Ptr pointer;
    typedef Ref reference;
    typedef __list_node<T>* link_type;
    link_type node;
    bool operator==(const self& x)const{return node == x.node};
    bool operator!=(const self& x)const{return node != x.node};
    reference operator*() const{return (*node).data};
    pointer operator->() const{return &(operator*());}//operator*() 是调用上面的函数operator*()
    self& operator++(){node = (link_type)((*node).next);return node;}
    self& operator++(int ){self tmp=* this; ++*this;return tmp}
    self& operator--(){node = (link_type)((*node).prev);return node}
    self& operator--(int){self tmp=*this; --*this;return tmp}
    }

仿函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
template <class T>
struct identity :public unary_function<T,T>{
const T&;
operator() (const T& x)const{return x;}
}

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

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

tempalate <class Arg,class Result>
struct unary_function{
typedef Arg argument_type;
typedef Result result_type;
}

template <class Arg1,class Arg2,class Result>
struct binary_function{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
}

源代码

1
2
3
4
5
6
7
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(d){}
};