c++ - shared_ptr not reporting referenced object deletion -
i'm running code in ms visual studio 10,
#include <iostream> #include <memory> using namespace std; class { int i; public: a(int j) : i(j) {} ~a() {} void fun() { cout << "a::i = " << << endl; } }; int _tmain(int argc, _tchar* argv[]) { aobj(12); std::shared_ptr<a> const pobj (&aobj, [] (a* pa) { cout << "lambda deleter" << endl; }); aobj.~a(); pobj->fun(); return 0; }
this prints / holds data members object, has been deleted, without reporting type of error.
please write on:
- why
shared_ptr
pobj doesn't report (at run-time) underlying object has been deleted? - since i'm creating const shared_ptr, means can't use refer other object, why lambda not invoked @ object deletion.
- can
weak_ptr
helpful in similar cases.weak_ptr
used semantics lifetime of reference object outlives object refers to.
why shared_ptr pobj doesn't report (at run-time) underlying object has been deleted?
because shared_ptr
not magic1. knows when contained object has been deleted when it deletes object. when use shared_ptr
, have entered contract shared_ptr
. 1 of tenants of contract (indeed, of any contract enter smart pointer of kind) you don't delete pointer. shared_ptr
instance owns pointer, , it delete it, not you.
violating contract leads undefined behavior.
since i'm creating const shared_ptr, means can't use refer other object, why lambda not invoked @ object deletion.
again, shared_ptr
can know contained object deleted when it deletes it. knows nothing state of object if break contract.
can weak_ptr helpful in similar cases. weak_ptr used semantics lifetime of reference object outlives object refers to.
weak_ptr
no more magically endowed shared_ptr
. weak_ptr
knows shared_ptr
set created knows about. if shared_ptr
doesn't know object's been deleted, weak_ptr
won't either.
1 "magic", mean doing that's not possible in c++. if want know function has been called (and destructor function call), there 2 ways that. either function tells it's been called (by setting value can see), or set system whereby people call function calls other function.
the first system requires function written explicitly let people know it's been called. can't old function; has designed that. second system requires use new function , nobody uses old one. if uses old 1 directly, code won't know it.
the first method called "intrusive" (because requires write object in special way), , smart pointers use called "intrusive smart pointers". second method non-intrusive (doesn't require special code object). shared_ptr
, , standard smart pointers, non-intrusive. means can use them object, can use them if abide contract.
c++ not offer third way. therefore, class somehow intrude on destructor call, class know has been called without destructor explicitly telling it has been, not possible. , therefore magic.
Comments
Post a Comment