zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    JSP学习笔记(一)
    【转】Key Presses
    【转】Event Driven Programming
    【转】Getting an Image on the Screen
    【转】Setting up SDL 2 on Visual Studio 2019 Community
    Windows定时任务copy到nfs目录
    DLL转存为IL文件及修改后重新生成DLL文件
    【转】Setting up SDL 2 on MinGW
    【转】Setting up SDL 2 on Code::Blocks 12.11
    【转】Setting up SDL on Windows
  • 原文地址:https://www.cnblogs.com/wanshuafe/p/11645266.html
Copyright © 2011-2022 走看看