zoukankan      html  css  js  c++  java
  • 《BOOST程序库完全开发指南》 第03章 内存管理

    auto_ptr、scoped_ptr 与 scoped_array:

    #include <iostream>
    #include <boost/scoped_ptr.hpp>
    #include <boost/scoped_array.hpp>
    #include <boost/shared_ptr.hpp>
    #include <boost/make_shared.hpp>
    
    class User
    {
        public:
            User(){}
    
        public:
            int id;
    };
    
    int main()
    {
        std::auto_ptr<int> ap(new int(3));
        std::cout<<*ap<<std::endl;
        std::auto_ptr<int> ap2 = ap;  //ok,同时ap失去控制权
        std::cout<<ap.get()<<std::endl; //0
    
        boost::scoped_ptr<int> sp(new int(3));
      //boost::scoped_ptr<int> sp2 = sp; //error,不能转移所有权
        std::cout<<*sp<<std::endl;
    
        //不推荐使用scoped_array,建议使用vector
        //scoped_array不能动态增长,没有迭代器支持,不能搭配stl算法。
         boost::scoped_array<int> sa(new int[100]);
        sa[1] = 2;
        std::cout<<sa[2]<<std::endl;
        std::cout<<sa[1]<<std::endl;
    
        //使用 boost::make_shared 可以包装 new 表达式,解决代码不对称性。
         boost::shared_ptr<User> user_ptr = boost::make_shared<User>();
        user_ptr->id = 3;
        std::cout<<user_ptr->id<<std::endl;
        std::cout<<user_ptr.get()->id<<std::endl; //get()方法可以获取原指针
    }
  • 相关阅读:
    机器人
    昨天拿钥匙了
    Linux挂NTFS格式USB硬盘
    漫游在首都
    RHEL+WAS6部署风波
    移动电话国内漫游通话费上限评估用户意见网上调查
    WebSphere fixes
    我太强悍了
    NO SUBJECT
    pku3617 Best Cow Line
  • 原文地址:https://www.cnblogs.com/tianyajuanke/p/2726137.html
Copyright © 2011-2022 走看看