Hi i am reading C++ primer 5th edition and i think i have spotted one error under the section shared_ptr. First i am writing the code and the explanation that they have given. Then i will write what i think is the error and what i think is actually happening. The code is as follows:
shared_ptr<int> p(new int(42));// reference count is 1
int *q = p.get();// ok: but don't use q in any way that might delete its pointer
{//new block started
shared_ptr<int>(q);
}// block ends, q is destroyed, and the memory to which q points is freed
int foo = *p;// undefined; the memory to which p points was freed
The explanation they have given is as follows:
In this case, both p and q point to the same memory. Because they were created independently from each other, each has a reference count of 1. When the block in which q was defined ends, q is destroyed. Destroying q frees the memory to which q points. That makes p into a dangling pointer, meaning that what happens when we attempt to use p is undefined. Moreover, when p is destroyed, the pointer to that memory will be deleted a second time.
Now i think the error is the statement "When the block in which q was defined ends, q is destroyed.Destroying q frees the memory to which q points." and also the reasoning they gave behind why p is a dangling pointer is faulty. Below is my reasoning why p is a dangling pointer and why first quoted statement is an error.
- When the block in which q was defined ends,
q
is destroyed. But the memory to whichq
points is not freed sinceq
is a builtin pointer and not a shared_ptr. And unless we explicitly write deleteq
the corresponding memory will not be freed. - Now, inside the new block we have created a temporary shared_ptr using q. But this temporary is independent of
p
. and so when this inner block ends the temporary is destroyed and hence the memory is freed. But note thatp
still point to the same memory which has been freed. Sop
is now a dangling pointer and usingp
in the statementint foo=*p
is undefined.
I think this is the correct explanation of why p is a dangling pointer and also the correction that should be there. Can someone confirm if this is right or am i doing something wrong?