• c++ 智能指针的使用


    https://www.cnblogs.com/TenosDoIt/p/3456704.html

    #include <QCoreApplication>
    #include <string>
    #include <iostream>
    #include <memory>
    
    using namespace  std;
    
    class Test
    {
    public:
        Test(string s)
        {
            str = s;
           cout<<"Test creat : " << str << endl;
        }
        ~Test()
        {
            cout<<"Test delete:"<<str<<endl;
        }
        string& getStr()
        {
            return str;
        }
        void setStr(string s)
        {
            str = s;
        }
        void print()
        {
            cout<<str<<endl;
        }
    private:
        string str;
    };
    
    unique_ptr<Test> fun()
    {
        return unique_ptr<Test>(new Test("789"));
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        auto_ptr<Test> ptest0(new Test("123"));
        ptest0->setStr("hello ");
        ptest0->print();
        ptest0.get()->print();
        ptest0->getStr() += "world !";
        (*ptest0).print();
        ptest0.reset(new Test("123"));
        ptest0->print();
        cout << "
    ";
    
        unique_ptr<Test> ptest1(new Test("123"));
        unique_ptr<Test> ptest2(new Test("456"));
        ptest1->print();
        ptest2 = std::move(ptest1);//不能直接ptest2 = ptest1
        if(ptest1 == NULL)cout<<"ptest = NULL
    ";
        Test* p = ptest2.release();
        p->print();
        ptest1.reset(p);
        ptest1->print();
        ptest2 = fun(); //这里可以用=,因为使用了移动构造函数
        ptest2->print();
        cout << "
    ";
    
    
        shared_ptr<Test> ptest(new Test("123"));
        shared_ptr<Test> ptest23(new Test("456"));
        cout<<ptest23->getStr()<<endl;
        cout<<ptest23.use_count()<<endl;
        ptest = ptest23;//"456"引用次数加1,“123”销毁
        ptest->print();
        cout<<ptest23.use_count()<<endl;//2
        cout<<ptest.use_count()<<endl;//2
        ptest.reset();
        ptest23.reset();//此时“456”销毁
        cout<<"done !
    ";
    
        return a.exec();
    }
  • 相关阅读:
    Gitlab forbidden
    oracle查询directory_path
    oracle_backup
    oracle
    客户端读取图片文件
    Sql游标的使用
    Sql解锁 数据库死锁检测
    css3d总结
    Redis在Linux系统下的安装和启动
    Linux系统基本操作命令
  • 原文地址:https://www.cnblogs.com/nanqiang/p/11974661.html
Copyright © 2020-2023  润新知