zoukankan      html  css  js  c++  java
  • pointer-like classes, 关于智能指针

    一个C++的class,做出来后,可能会像两种东西。

    1. 所产生出来的对象一个指针。所以叫做pointer-like classes.
    2. 所产生出来的对象像一个函数,有点特别哦。

    为何设计一个类产生的对象要像一个指针,因为你想要它做比指针更多的事情,所以通常这样做出来的东西,又叫做智能指针(更聪明的指针)。

    #pragma once
    class share_ptr
    {
    public:
        T& operator*() const
        {return *px;}
        T* operator->() const
        {return px;}
        shared_ptr(T* p): px(p){}
    private:
        T* px;
        long* pn;
    ......
    };

    注解:

    1. T* px; px是指向T类型的指针。
    2. C++里面的操作符重载是很常见的,且是很重要和强大的。智能指针的这两个写法几乎是固定的。
    3. 聪明的指针都会有这么一个构造函数:
      shared_ptr(T* p): px(p){}
    4. 这个构造函数的参数接受天然的指针,C++的指针。
    struct Foo
    {
        ......
            void method(void) {......}
    };
    shared_ptr<Foo> sp(new Foo);
    Foo f(*sp);
    sp->method();
    px->method();

    注解:

    1. 假设现在写了一个Class,叫做Foo, 要把Foo这种天然的指针(new Foo,new就是得到一根指针)包装到这个聪明的指针里面去,即shared_ptr指针里面。
    2. sp->method();   智能指针调用method()方法。操作符'->'属于调用操作符重载哦。这句就相当于px->method(). 操作符->作用在指针对象sp上,得到指针对象px。
    • 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 pointer;
        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).prep); return *this }
        self& operator--(int) { self tmp = *this; --*this; return tmp; }
    };
  • 相关阅读:
    python-44-初识队列
    python-43-进程锁/信号量/事件
    python-42-Process多进程
    python-41-初识hmac与socketserver模块
    python-40-初识socket与struct
    python-39-hashlib与logging模块
    python-38-用于面向对象的内置函数
    python-37-各种反射
    python-36-封装与面向对象函数
    python-35-多态与初识封装
  • 原文地址:https://www.cnblogs.com/yibeimingyue/p/13514956.html
Copyright © 2011-2022 走看看