C++中的智能指针学习笔记

时间:2019-04-03 00:48:19   收藏:0   阅读:203

一、学习总结

1.一个非const引用无法指向一个临时变量,但是const引用是可以的!

2.C++中的delete和C中的free()类似,delete NULL不会报"double free"的oops。

int main(int argc, char **argv)
{    
    int i;
    int *p = new int;
    delete p;
    p = NULL;
    delete p;
    return 0;
}

3.智能指针的实现思想:使用可以自动销毁的局部对象来描述不可以自动销毁的位于堆空间中的对象指针,以达到不需要考虑释放内存,避免内存泄漏的目的。

4.使用智能指针的限制:想使用智能指针处理一个对象,这个对象必须要继承RefBase类, 以便智能指针能操作类提供引用计数操作!

 

二、实例代码

#include <iostream>

using namespace std;


class RefBase {
private:
    int refcount;
public:
    RefBase() : refcount(0) {}

    void incStrong(void) {
        refcount++;
    }
    void decStrong(void) {
        refcount--;
    }
    int getStrong(void) {
        return refcount;
    }    
};

class Person : public RefBase {
public:
    Person() {
        cout << "Person()" << endl;
    }
    ~Person() {
        cout << "~Person()" << endl;
    }
    void printInfo() {
        cout << "printInfo()" << endl;
    }
};

/*---------------define----------*/
template<typename T>
class sp {
private:
    T *p;

public:
    sp() : p(NULL) {
        cout << "sp()" << endl;
    }

    sp(T *p) {
        cout << "sp(T *p)" << endl;
        this->p = p;
        this->p->incStrong();
    }

    sp(const sp & other) {
        cout << "sp(const sp & other)" << endl;
        this->p = other.p;
        this->p->incStrong();
    }

    ~sp() {
        cout << "~sp()" << endl;
        this->p->decStrong();
        if (!this->p->getStrong()) {
            delete p; //atomic call ~Person()
            cout << "delete p" << endl;
        }
    }

    T* operator->() {
        return this->p;
    }
    T& operator*() {
        return *(this->p);
    }
};


/*-----------------usage------------------*/
void test_func(sp<Person>& p) {
    sp<Person> p1 = p;

    p1->printInfo();

    (*p1).printInfo();

    sp<Person> p2 = new Person();

    sp<Person> p3 = new Person();
}

int main() 
{
    sp<Person> p1 = new Person();

    for (int i = 0; i < 2; i++) {
        cout << "-------" << i << "-------" << endl;
        test_func(p1);
        cout << "-------" << "-" << "-------" << endl;
    }

    cout << "-------end main()---------" << endl;
}

 

原文:https://www.cnblogs.com/hellokitty2/p/10646353.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!