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;
    }

    输出:

  • 相关阅读:
    Oracle数据库5--数据库对象
    Oracle数据库4--多表关联
    Session
    cookie
    Servlet的部分response响应处理
    Servlet的部分request请求处理
    Linux部分命令
    Linux基础
    弹性布局
    animation 动画
  • 原文地址:https://www.cnblogs.com/heben/p/9528650.html
Copyright © 2011-2022 走看看