智能指针tr1::shared_ptr、boost::shared_ptr使用

2023-05-16

对于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

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

智能指针tr1::shared_ptr、boost::shared_ptr使用 的相关文章

随机推荐