• 智能指针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

  • 相关阅读:
    008-解决sublime text3安装Package Control问题
    156-a++与++a区别?
    155-类型转换的六条规则是什么?
    040-springboot工程无法逆向工程生成?
    153-如何搭建springboot框架?
    【根据生日获取年龄】
    富文本 保存转义StringEscapeUtils.unescapeHtml4(
    git ,报403错误,完美解决方案
    idea创建Maven项目后启动报404
    IntelliJ IDEA2016.1 + maven 创建java web 项目[转]
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6781085.html
Copyright © 2020-2023  润新知