C++智能指针

智能指针介绍

C++在堆上申请的内存,需要程序员自己去手动释放,这个内存很容易忘记释放或者在释放之前遭遇了异常,造成内存泄露。
堆内存的多次释放,会造成程序崩溃,同样,访问已经释放的内存也会造成不可预期的错误,而这些问题,都可以用智能指针来解决。
智能指针,主要用于堆内存的管理,在堆上生成的对象,可由智能指针进行管理,程序员无需手动释放,堆上的内存。

智能指针简易代码实现

使用引用计数法,当对象的引用次数为0时,会去释放相应的内存资源

#include<iostream>
template < typename T >
class SmartPointer {
  public:
  SmartPointer(T * p):ptr_(p) {
	std::cout << "create smart pointer" << std::endl;
	user_count_ = new int (1);

    }
    SmartPointer(const SmartPointer & s_ptr) {
	std::cout << "copy constructor is called" << std::endl;
	ptr_ = s_ptr.ptr_;
	user_count_ = s_ptr.user_count_;
	++(*user_count_);
    }

    SmartPointer & operator=(const SmartPointer & s_ptr) {
	std::cout << "Assignment constructor is called" << std::endl;
	if (this == &s_ptr) {
	    return *this;
	}

	--(*user_count_);
	if (!(*user_count_)) {
	    delete ptr_;
	    ptr_ = nullptr;
	    delete user_count_;
	    user_count_ = nullptr;
	    std::cout << "left side object is called" << std::endl;
	}

	ptr_ = s_ptr.ptr_;
	user_count_ = s_ptr.user_count_;
	++(*user_count_);
    }

    ~SmartPointer() {
	std::cout << "Destructor is called" << std::endl;
	--(*user_count_);
	if (!(*user_count_)) {
	    delete ptr_;
	    ptr_ = nullptr;
	    delete user_count_;
	    user_count_ = nullptr;
	}

    }

  private:
    T * ptr_;
    int *user_count_;
};

int main()
{
    SmartPointer < int >ptr1(new int (10));
    ptr1 = ptr1;
    SmartPointer < int >ptr2(ptr1);
    SmartPointer < int >ptr3(new int (20));
    ptr3 = ptr1;
}

posted on 2019-10-10 00:37  盛夏落木  阅读(157)  评论(0编辑  收藏  举报

导航