c++ - when the shared pointers gets destroyed? -
i reading following piece of code explained 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 same resource // sp destroyed here, yet no freeing: sp2 still alive } cout << "out of inner block" << endl; // sp2 destroyed here, reference count goes 0, memory freed } my question is, how come both pointers point same resource myclass& obj2 = *sp;? , why sp destroyed @ point reach comment // sp2 destroyed here, reference count goes 0, memory freed?
my question how come both pointers point same resource
myclass& obj2 = *sp;?
that not make sense. meant:
myclass& obj2 = *sp2; // ok, both pointers point same resource ^^^ sp2, not sp and why
spdestroyed @ the place commented?
that's because sp constructed in nested scope introduced
shared_ptr<myclass> sp2; { // starts new scope .... } // ends scope at end of nested scope, automatic variables destructed.
from standard:
3.7.3 automatic storage duration [basic.stc.auto]
1 block-scope variables explicitly declared
registeror not explicitly declaredstaticorexternhave automatic storage duration. storage these entities lasts until block in created exits.
Comments
Post a Comment