c++ - How is the deletion of a pointer detected using dynamic cast -


as shown here, 1 can use dynamic_cast detect deleted pointer:

#include <iostream>  using namespace std;  class { public:    a() {}    virtual ~a() {} };  class b : public { public:    b() {} };  int main() {    b* pb =  new b;     cout << "dynamic_cast<b*>( pb) ";    cout << ( dynamic_cast<b*>(pb) ? "worked" : "failed") << endl;       cout << "dynamic_cast<b*>( (a*)pb) ";    cout << ( dynamic_cast<b*>( (a*)pb) ? "worked" : "failed") << endl;       delete pb;      cout << "dynamic_cast<b*>( pb) ";    cout << ( dynamic_cast<b*>(pb) ? "worked" : "failed") << endl;       cout << "dynamic_cast<b*>( (a*)pb) ";    cout << ( dynamic_cast<b*>( (a*)pb) ? "worked" : "failed") << endl;    } 

the output:

dynamic_cast<b*>( pb) worked dynamic_cast<b*>( (a*)pb) worked dynamic_cast<b*>( pb) worked dynamic_cast<b*>( (a*)pb) failed 

it explains deletion of vtable detected.

but wondering how possible since not overwrite freed memory?

and solution portable ?

thanks

first off, trying use deleted object in form results in undefined behavior: whatever result see happen!

the reason of observed behavior object changes type during destruction: being object of concrete type change through of types in hierarchy. @ each point virtual functions change , vtable (or similar) gets replaced. dynamic_cast<...>() detects change in bytes strored @ location of object.

in case feel wanting show technique doesn't reliably work can set content of deleted memory random bit pattern or bit pattern of object of derived type: random bit pattern yields crash , memcpy() claims object still life. of course, since undefined behavior can happen.

one relevant section on 3.8 [basic.life] paragraph 5:

before lifetime of object has started after storage object occupy has been allocated or, after lifetime of object has ended , before storage object occupied reused or released, pointer refers storage location object or located may used in limited ways. object under construction or destruction, see 12.7. otherwise, such pointer refers allocated storage (3.7.4.2), , using pointer if pointer of type void*, well-defined. indirection through such pointer permitted resulting lvalue may used in limited ways, described below. program has undefined behavior if:

  • ...
  • the pointer used operand of dynamic_cast (5.2.7). ...

oddly, example on last bullet on dynamic_cast doesn't use dynamic_cast.

of course, object released in case above guarantees don't apply.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -