Fork me on GitHub

c++ 智能指针

智能指针,是模板类,意在避免在使用动态内存时,出现异常等意外,或忘记使用delete,而造成内存泄漏。
这个智能指针,在指针变量结束声明周期后,调用对象的析构函数,并自动去释放这个指针指向的内存块。
智能指针我了解的有auto_ptr、unique_ptr、shared_ptr,各有特点。
{
        std::auto_ptr<Report> ps(new Report("using auto_ptr"));
        ps->comment();
    }
    {
        std::unique_ptr<Report>ps(new Report("using unique_ptr"));
        ps->comment();
    }
    {
        std::shared_ptr<Report>ps(new Report("using shared_ptr"));
        ps->comment();
    }
一、auto_ptr与unique_ptr的比较
这两个都是独享指针。auto_ptr 不能创建 std::auto_ptrdArr(new double[1])这种类型的指针变量。
std::auto_ptr<Report>autoR1(new Report("test Auto"));
    std::auto_ptr<Report>autoR2;
    autoR2 = autoR1;
   // autoR1->comment();
这里的代码 autoR2 = autoR1;作为普通的指针,没有深拷贝函数,赋值之后,autoR1就成了悬挂指针,已经不指向原来的内存了。编译能通过,去掉注释报运行错误。
std::unique_ptr<Report>uPs(new Report("test unique_ptr"));
    std::unique_ptr<Report>uPs2;
   // uPs2 = uPs; //编译通不过
unique_ptr像上面那样赋值,直接通过不编译。可以创建std::unique_ptrarr(new int[5]);这种指针变量
二、shared_ptr
有一个引用计数。
std::shared_ptr<int[]>arr2(new int[3]);
    arr2[0] = 2;
    std::cout << arr2[0] << "\n";
    std::shared_ptr<int[]>arr3 = arr2;
    arr3[0] = 4;
    std::cout << arr2[0] << "\n";
arr3=arr2,这里,引用计数加1.只有当引用计数为0的时候,才会释放这些分享指针指向的内存位置。
所以这里赋值不会有悬挂指针。
测试环境 vs2019及默认的编译器版本。
posted @ 2022-08-22 20:33  HelloLLLLL  阅读(87)  评论(0)    收藏  举报