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;
    }
    
  • 相关阅读:
    Unity3D性能优化--- 收集整理的一堆
    Unity5.3官方VR教程重磅登场-系列7 优化VR体验
    VR沉浸体验的要求
    Unity5中叹为观止的实时GI效果
    浅谈控制反转与依赖注入[转]
    unity 使用unityaction 需要注意的问题[转]
    c# orm框架 sqlsugar
    unity Instantiate设置父级物体bug
    宝塔面板 使用mongodb注意事项
    unity中gameObject.SetActive()方法的注意事项。
  • 原文地址:https://www.cnblogs.com/wanshuafe/p/11645266.html
Copyright © 2011-2022 走看看