勿在浮沙筑高台--P17-18

一. pointer-like classes 智能指针

  • 把c++天然的指针包含到智能指针里。
  • '->'符号消耗掉还会作用下去。
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){....}
};

shared_ptr<Foo> sp(new Foo);
Foo f(*sp);
sp->method();  //px->method(); '->'符号消耗掉还会作用下去。

二. pointer-like classes 迭代器, 也是智能指针

  • ++ --只存在于指针移动
template<class T, class Ref, class Ptr>
struct __list_iterator{
    typedef __list_iterator<T, Ref, Ptr> self;
    typedef Ptr pointer;
    typedef Ref refernce;
    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*()); }
    self& operator++(){node = (link_type)((*node).next); return *this; }
    self operator++(int){self tmp = * this; ++*this; return tmp; }
    self& operator--(){node = (link_type)((*node).prev); return *this; }
    self operator--(int){self tmp = * this; --*this; return tmp; }
};

template<class T>
struct __list_node{
   void* prev;
   void* next;
   T data;
};
list<Foo>::iterator ite;
...
*ite;     //获得一个Foo object
ite->method;
  //意思是调用Foo::method();
  //相当于(*ite).method();
  //相当于&(*ite)->method();

三. function-like classes, 仿函数

  • 重载()就是想做成仿函数。
  • 待续
template<class T>
struct identity{
    const T&
    operator()(const T& x) const{return x;}
};
template<class Pair>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容