I am reading the following piece of code as explained by the comments.
#include <memory>
struct myClass {
~myClass() {
cout << "dtor" << endl;
}
};
void myFunc() {
shared_ptr<myClass> sp2;
{
shared_ptr<myClass> sp( new myClass);
myClass& obj = *sp;
sp2 = sp; // OK, resource shared
myClass& obj2 = *sp; // OK, both pointers point to same resource
// sp destroyed here, yet no freeing: sp2 still alive
}
cout << "out of inner block" << endl;
// sp2 destroyed here, reference count goes to 0, memory is freed
}
My question is, how come both pointers point to same resource for myClass& obj2 = *sp;
? And why is sp
destroyed at point where we reach the comment // sp2 destroyed here, reference count goes to 0, memory is freed
?
My question is that how come both pointers point to same resource for
myClass& obj2 = *sp;
?
That does not make sense. They probably meant:
myClass& obj2 = *sp2; // OK, both pointers point to same resource
^^^ sp2, not sp
And why
sp
is destroyed at the the place where as commented?
That's because sp
is constructed in a nested scope introduced by
shared_ptr<myClass> sp2;
{ // This starts a new scope
....
} // This ends the scope
At the end of the nested scope, all automatic variables are destructed.
From the standard:
3.7.3 Automatic storage duration [basic.stc.auto]
1 Block-scope variables explicitly declared
register
or not explicitly declaredstatic
orextern
have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.