zoukankan      html  css  js  c++  java
  • 智能指针tr1::shared_ptr、boost::shared_ptr使用

    对于tr1::shared_ptr在安装vs同一时候会自带安装,可是版本号较低的不存在。而boost作为tr1的实现品,包括
    “Algorithms
    Broken Compiler Workarounds
    Concurrent Programming
    Containers
    Correctness and Testing
    Data Structures
    Domain Specific
    Function Objects and Higher-order Programming
    Generic Programming
    Image Processing
    Input/Output
    Inter-language Support
    Iterators
    Language Features Emulation
    Math and Numerics
    Memory
    Parsing
    Patterns and Idioms
    Preprocessor Metaprogramming
    Programming Interfaces
    State Machines
    String and Text Processing
    System
    Template Metaprogramming
    Miscellaneous ”
    等一系列更安全、更丰富的c++函数或库的实现品。能够在官网下载,当中包括具体的API文档与例程。当中boost::shared_ptr是对tr1的shared_ptr的实现。作为智能指针(类指针对象)二者的用法相似。具体见下方代码。

    头文件

    #include <iostream>
    
    using namespace std;
    
    class Test
    {
    public:
    	Test();
    	~Test();
    };


    实现文件

    #include "head.h"
    
    Test::Test()
    {
        cout << "construct Test." << endl;
    }
    
    Test::~Test()
    {
        cout << "destruct Test." << endl;
    }


    main文件

    //boost中shared_ptr头文件
    #include <boost/shared_ptr.hpp>
    
    //vs2005一并中安装的库是不带shared_ptr的
    #include <memory>
    #include "head.h"
    
    //实验tr1::shared_ptr
    void test_shared_ptr()
    {
        cout << "I am tr1." << endl;
        tr1::shared_ptr<Test> p_test(new Test());
    }
    
    //实验boost/shared_ptr
    void test_boost_shared_ptr()
    { 
    	cout << "I am boost." << endl;
    	boost::shared_ptr<Test> p_boost_test(new Test());
    }
    
    
    int main()
    {
        test_shared_ptr();
        cout << "**************************" << endl;
    	test_boost_shared_ptr();
    
    	system("pause");
    }


     

    运行效果:


    上述两种方式是使用对象管理资源的最佳实现。标准库也提供了auto_ptr,可是这样的对象不可以复制。

    对于使用对象管理资源的思路,C++t推荐的原则是RAII,即Resource aquisition is initialasition。

    ***************************************************************************

    原创,本文链接:http://blog.csdn.net/u012150179/article/details/37965931

  • 相关阅读:
    MCMC等采样算法
    【模拟退火】旅行商问题
    团队项目博客汇总
    2018年春季学期-助教总结
    linux简单命令常用随记
    记一次计算机网络作业
    [东北师大软工]Week2-作业2:个人项目实战 初步测试结果
    为什么你学过Java却忘光了——记第一次助教同学见面会
    ahk打印成pdf记录
    PSP总结报告
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6781085.html
Copyright © 2011-2022 走看看