zoukankan      html  css  js  c++  java
  • c++ 智能指针

    1.auto_ptr(虽然可以使用,但该方式已经被c++11摈弃)

    #include<iostream>
    #include<string>
    #include<memory>
    using namespace std;
    
    //double所在的内存没有机会被释放,将造成内存泄漏
    void demo1()
    {
        double* pd = new double();
        *pd = 25.5;
    }
    
    //ap自带析构函数,声明周期结束时将自动调用析构桉树,释放掉指向的内存
    void demo2()
    {
        auto_ptr<double> ap(new double);
        *ap = 25.5;
    }
    
    int main(void)
    {
        demo1();
        demo2();
    
    
        cin.get();
        return 0;
    }

    shared_ptr 、 unique_ptr 的用法和 auto_ptr用法是一样的:

    #include<iostream>
    #include<string>
    #include<memory>
    using namespace std;
    
    class Report
    {
    private:
        string str;
    public:
        Report(const string s) :str(s)
        {
            cout << "Object created." << endl;
        }
        ~Report()
        {
            cout << "Object deleted." << endl;
        }
        void comment() const
        {
            cout << str << endl;
        }
    };
    
    int main(void)
    {
        {
            auto_ptr<Report> ps(new Report("using auto_ptr"));
            ps->comment();
        }
    
        {
            shared_ptr<Report> ps(new Report("using shared_ptr"));
            ps->comment();
        }
    
        {
            unique_ptr<Report> ps(new Report("using unique_ptr"));
            ps->comment();
        }
    
        cin.get();
        return 0;
    }

    输出:

  • 相关阅读:
    docker创建tomcat容器
    【转载】张一鸣:为什么 BAT 挖不走我们的人才?
    Elastic认证考试,请先看这一篇
    vs code 初始化vue项目框架
    Idea集成git常用命令
    pxc搭建mysql集群
    mysql无限级分类
    Java面试题大全
    SpringMVC和Spring
    Redis高级特性
  • 原文地址:https://www.cnblogs.com/heben/p/9528650.html
Copyright © 2011-2022 走看看