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

  • 相关阅读:
    爱情七十八课,闲了就“犯贱”
    阿里巴巴中文站的CSS设计规则(转)
    爱情八十一课,可预测的分手
    [性格][管理]《九型人格2》 唐·理查德·里索(美)、拉斯·赫德森(美)
    爱情八十二课,爱情三国杀
    爱情七十九课,不爱权力大
    [心理学]《爱情心灵安全岛》 四四
    一些你不知道的囧知识,保证让你崩溃
    爱情七十四课,我们的意义
    爱情七十六课,门当户对
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6781085.html
Copyright © 2011-2022 走看看