智能指针是为了便于管理动态内存,能够自动管理释放所指向的对象。
智能指针共有三种:1、shared_ptr允许多个指针指向同一个对象;2、unique_ptr独占所指向的对象;3、weak_ptr是一个伴随类,它是一种弱引用,指向shared_ptr所管理的对象。这三种类型都定义在memory头文件中。
下面是一个在网上看到的智能指针的实现原理代码:
class U_Ptr { friend class HasPtr; int *ip; size_t use; U_Ptr(int *p) : ip(p), use(1) { cout << "U_ptr constructor called !" << endl; } ~U_Ptr() { delete ip; cout << "U_ptr distructor called !" << endl; } }; class HasPtr { public: HasPtr(int *p, int i) : ptr(new U_Ptr(p)), val(i) { cout << "HasPtr constructor called ! " << "use = " << ptr->use << endl; } HasPtr(const HasPtr& orig) : ptr(orig.ptr), val(orig.val) { ++ptr->use; cout << "HasPtr copy constructor called ! " << "use = " << ptr->use << endl; } HasPtr& operator=(const HasPtr&); ~HasPtr() { cout << "HasPtr distructor called ! " << "use = " << ptr->use << endl; if (--ptr->use == 0) delete ptr; } int *get_ptr() const { return ptr->ip; } int get_int() const { return val; } void set_ptr(int *p) const { ptr->ip = p; } void set_int(int i) { val = i; } int get_ptr_val() const { return *ptr->ip; } void set_ptr_val(int i) { *ptr->ip = i; } private: U_Ptr *ptr; int val; }; HasPtr& HasPtr::operator =(const HasPtr &rhs) { //注意,这里赋值操作符在减少做操作数的使用计数之前使rhs的使用技术加1,从而防止自我赋值 ++rhs.ptr->use; if (--ptr->use == 0) delete ptr; ptr = rhs.ptr; val = rhs.val; return *this; }