c++ - Calling `shared_ptr.get()` vs copy-initialization, what's the difference? -
first version print use_count = 2;
shared_ptr<int> s{make_shared<int>(15)}; auto b = s; cout<<s.use_count()<<endl; auto c = s.get(); cout<<s.use_count()<<endl; cout<<*c<<endl; second version use_count = 3;
shared_ptr<int> s{make_shared<int>(15)}; auto b = s; cout<<s.use_count()<<endl; auto c = s; cout<<s.use_count()<<endl; cout<<*c<<endl; question:
- why behavior different between 2 versions?
introduction
every time make copy of shared_ptr use-count increased since have additional handle underlying resource being tracked.
in order obtain value of underlying pointer, shared_ptr has member-function named get. function return address of tracked resource, not create additional shared_ptr tracking same pointer.
potential dangers
in first snippet have 2 instances of shared_ptr refers same resource, in latter have three.
the difference being;
auto = screate copy ofs, , type ofaofs(a shared_ptr)auto b = s.get ()initializebaddress of tracked resource manageds, hence raw-pointer.
if don't know doing, calling .get () might dangerous, can seen in following snippet.
int * ptr = nullptr; { std::shared_ptr<int> sp { make_shared<int> (15) }; ptr = sp.get (); } std::cout << *ptr << std::endl; // (a), dangling pointer inside our nested scope create shared_ptr named sp, , ask keep track of int dynamic storage duration created our call make_shared.
we obtain address of int calling sp.get (), , assign ptr.
when scope of sp ends, sp release resource managed since there's no more *shared_ptr*s refers it.
by trying print value of *ptr invoking undefined behavior in (a) since value isn't available, destroyed destruction of sp.
Comments
Post a Comment