c++_primer_exercise_1210

来源:互联网 发布:数据降维 量子多体 编辑:程序博客网 时间:2024/06/03 19:13

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 namedget that returns a built-in pointerto 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
原创粉丝点击