c++_primer_exercise_1210

Answer to Exercise 12.10:

In this call, we passed a temporary shared_ptr to process. That temporary is destroyed when the expression in which the call appears finishes. Destroying the temporary decrements the reference count, which goes to zero. The memory to which the temporary points is freed when the temporary is destroyed.

But p continues to point to that (freed) memory; p is now a dangling pointer. Attempting to use the value of p is undefined.


Answer to Exercise 12.11:

Like 12.10, what we passed to process is s temporary shared_ptr. In process, ptr has a reference count of 1. When the call finishes, ptr is destroyed. Destroying ptr decrements the reference count, which goes to zero. The memory to which ptr points is freed when ptr is destroyed.

But p continues to point to that (freed) memory; p is now a dangling pointer. Attempting to use the value of p is undefined.

(additional information: The smart pointer types define a function named get that returns a built-in pointer to the object that the smart pointer is managing. This function is intended for cases when we need to pass a built-in pointer to code that can't use a smart pointer.)


Answer to Exercise 12.12:

(a), okay. 

(b), illegal. We cannot implicitly convert a built-in pointer to a smart pointer; we must use the direct from of initialization to initialize a smart pointer.

(c), illegal. Reasons as (b). vs2013: cannot convert argument 1 from 'int *' to 'std::shared_ptr<int>'

(d), legal, but it may cause problems. See Answer to Exercise 12.10.


Answer to Exercise 12.13:

When p is destroyed, the pointer to that memory will be deleted a second time.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值