智能指针scoped_ptr

scoped_ptr特点:

1 用法绝大多数情况下和auto_ptr相同。

2 不支持自增,自减操作。

3 不能被赋值或者复制构造。

4 由于3的原因不能作为容器的元素,这也是优于auto_ptr的原因。

scoped_ptr使用场景:

1 在有可能抛出异常的作用域中使用时,减少有可能资源释放不正确导致的错误。

2 函数中控制路径多并且复杂时,减少代码的逻辑阅读难度和资源释放有可能带来的错误。

3 动态分配对象的生命周期限制在特定的作用域,采用scoped_ptr可以有作用域保护。

4 异常安全非常重要的时候,作用类似于1

演示代码:

 

// scoped_ptr.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <boost/scoped_ptr.hpp>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
using namespace boost;

void scoped_vs_auto();

int _tmain(int argc, _TCHAR* argv[])
{
	// 正常用法
	scoped_ptr<string> p(new string("User scoped_ptr often."));
	if (p)
	{
		cout << *p << '\n';
		cout << "sizeof(\"" << *p << "\") = " << p->size() << endl;
		*p = "Acts just like a pointer";
		cout << "After Change:" << endl;
		cout << "sizeof(\"" << *p << "\") = " << p->size() << endl;
	}

	// 自增自减操作——不支持
	//p++;
	//p--;

	// scoped_ptr和auto_ptr的比较
	// scoped_ptr不能被赋值或复制构造
	scoped_vs_auto();
	
	// 因为不支持赋值和复制构造,所以不能作为容器的元素
	//vector<scoped_ptr<string>> vecp;
	//vecp.push_back(p);

	// scoped_ptr
	getchar();
	return 0;
}


void scoped_vs_auto()
{
	scoped_ptr<string> p_scoped(new string("hello"));
	auto_ptr<string> p_auto(new string("hello"));
	p_scoped->size();
	p_auto->size();
	// 编译不通过,不能被赋值
	//scoped_ptr<string> p_another_scoped = p_scoped;
	auto_ptr<string> p_another_auto = p_auto;
	p_another_auto->size();
	(*p_auto).size();
}


你可能感兴趣的:(String,user)