c++ - smart pointers in multi-threaded envrionment -


i new smart pointers. however, have basic understanding of it. i've observed is necessary smart pointers destroyed in reverse order of creation or else smart pointers may misbehave. consider below situation:

sharedptr<abc> my_ptr(new abc); //smart pointer created. instance counter = 1. func1(my_ptr);                  //copy constructor in smart pointer called. instance    counter=2 func2(my_ptr);                  //copy constructor in smart pointer called. instance counter=3 func3(my_ptr);                  //copy constructor in smart pointer called. instance counter=4 

now, isn't necessary func3() exits first followed func2(), func1() , my_ptr.

question: if my_ptr goes out of scope first (& hence tries delete abc), func1(), func2() , func3() still referring abc (through smart pointers) ?

actually, observed wrong.

the point of smart pointer remove responsibility of destroying object. means object delete when reference count reach 0: it doesn't matter pointer destructed first.

in case, when my_ptr goes out of scope (assuming don't make , keep copy in 1 func().

this reference counter should be:

{ sharedptr<abc> my_ptr(new abc); //smart pointer created. ref counter = 1. func1(my_ptr);                  // ref counter=2 while in func1 // ref count 1 again. func2(my_ptr);                  // ref counter=2 while in func2 // ref count 1 again. func3(my_ptr);                  // ref counter=2 while in func3 // ref count 1 again. } // my_ptr goes out of scope, ref count reach 0, , abc deleted. 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -