c++ Dynamic Memory (part 2)

Don't use get to initialize or assign another smart pointer.

The code that use the return from get can not delete the pointer

Although the compiler will not complain, it is an error to build another smart pointer to the pointer returned by get

shared_ptr<int> p(new int(42));    // reference count is 1
int *q = p.get();    // ok; but do not delete its pointer
{
    shared_ptr<int> (q);
}    // block ends. q is destroyed, and the memory to which q points is freed
int f = *p;    // undefined. The memory to which p points is freed. 

 

Using Our Own Deletion Code

void end_connection(connection *p)
{
    disconnection(*p);
}

void f(destination &d)
{
    connection c = conn(&d);
    shared_ptr<connection p(&c, end_connection);
    // use the connection
    // when f exists, even if by an exception, the connection resource will be properly closed
}

 

For unique_ptr

Call release() breaks the connection between a unique_ptr and the object it had been managing. Ofter the pointer returned by release() is used to initialized or assign another pointer

unique_ptr<int> p2(new int(42));
p2.release();    // WRONG! P2 will not free the memory, and we have lose the pointer
auto p = p2.release();    // OK, but we must remember to delete p

 

Backward compatibilities auto_ptr

Although auto_ptr is still part of the standard library, programs should use unique_ptr instead.

 

转载于:https://www.cnblogs.com/TonyYPZhang/p/6854544.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值