shared_ptr or: How I Learn To Stop Worring and Love Resource Management

shared_ptr 是一个模板类

shared_ptr< T>

shared_ptr< const T>

const shared_ptr<const T>

Basic shared_ptr Use

std::shared_ptr<std::string> sp(new std::string("hello"));
std::cout << *sp << ", "<< sp->size() << std::endl;

输出结果为:hello, 5

Basic shared_ptr Error

std::shared_ptr<std::string> sp = new std::string("hello");
Compiler error (after substitution):
error C2440: 'initializing' : cannot convert from 'std::string *' to 'std::tr1::shared_ptr<std::string>'
Constructor for class 'std::tr1::shared_ptr<std::string>' is declared 'explicit'
注意:显式(explicit)而非隐式(implicit),错在 = 为隐式赋值;显式赋值: std::shared_ptr<std::string> sp(new std::string("hello"));

Using shared_ptr in Conditionals

std::shared_ptr<int> a;
std::shared_ptr<int> b(new int(137));

std::cout << (a ? "a" : "X") << std::endl;
if (b){
	std::cout << "b" << std::endl;
}
else{
	std::cout << "X" << std::endl;
}

输出为:X

              b

Returning shared_ptr By value

std::shared_ptr<int> foo(int n) 
{
	std::shared_ptr<int> r(new int(n));
	*r += 5;
	return r;
}
int main()
{
	std::shared_ptr<int> p = foo(3);
	std::cout << *p << std::endl;
}

输出为:8

Sharing Ownership with Shared_ptr

std::shared_ptr<int> a(new int (1));
std::shared_ptr<int> b = a;// a,b指向同一个对象

*a += 6;
std::cout << *a << ", " << *b << std::endl;//7, 7

a.reset();
std::cout << "a: " << (a ? "owns" : "empty") << std::endl;
std::cout << "b: " << (b ? "owns" : "empty") << std::endl;
std::cout << *b << std::endl;

// 输出
/*7, 7
a: empty
b : owns
7*/

shared_ptr<const T>

std::shared_ptr<int> frob(new int(100));
std::shared_ptr<const int> look = frob;
std::cout << *look << std::endl;
*frob /= 2;
std::cout << *look << std::endl;
// *look /= 2;// Error 不能给常量赋值

输出:100

          50








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值