fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct TObject
  5. {
  6. virtual ~TObject() = default;
  7. };
  8.  
  9. struct TDerived : TObject
  10. {
  11. ~TDerived() { cout << "TDerived destroyed" << endl; }
  12. };
  13.  
  14. void FreeAndNil(const TObject* const &Obj)
  15. {
  16. cout << "FreeAndNil: Obj=" << Obj << " &Obj=" << &Obj << endl;
  17. const TObject *temp = Obj;
  18. ((TObject*&)(*(void**)&Obj)) = nullptr;
  19. //reinterpret_cast<TObject*&>(const_cast<void*&>(*reinterpret_cast<const void * const *>(&ref))) = nullptr;
  20. //const_cast<TObject*&>(const_cast<const TObject * const &>(ref)) = nullptr;
  21. delete temp;
  22. }
  23.  
  24. void test(const TObject* Obj)
  25. {
  26. cout << "test: Obj=" << Obj << endl;
  27. }
  28.  
  29. int main()
  30. {
  31. const TObject *o1 = new TDerived;
  32. cout << "main: o1=" << o1 << " &o1=" << &o1 << endl;
  33. FreeAndNil(o1);
  34. cout << "main: o1=" << o1 << " &o1=" << &o1 << endl;
  35. test(o1);
  36.  
  37. cout << endl;
  38.  
  39. TObject *o2 = new TDerived;
  40. cout << "main: o2=" << o2 << " &o2=" << &o2 << endl;
  41. FreeAndNil(o2);
  42. cout << "main: o2=" << o2 << " &o2=" << &o2 << endl;
  43. test(o2);
  44.  
  45. cout << endl;
  46.  
  47. TDerived *o3 = new TDerived;
  48. cout << "main: o3=" << o3 << " &o3=" << &o3 << endl;
  49. FreeAndNil(o3);
  50. cout << "main: o3=" << o3 << " &o3=" << &o3 << endl;
  51. test(o3);
  52.  
  53. cout << endl;
  54.  
  55. const TDerived *o4 = new TDerived;
  56. cout << "main: o4=" << o4 << " &o4=" << &o4 << endl;
  57. FreeAndNil(o4);
  58. cout << "main: o4=" << o4 << " &o4=" << &o4 << endl;
  59. test(o4);
  60.  
  61. cout << endl;
  62.  
  63. FreeAndNil(nullptr);
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 4380KB
stdin
Standard input is empty
stdout
main: o1=0x55a5eb5e8e70 &o1=0x7ffdeb886450
FreeAndNil: Obj=0x55a5eb5e8e70 &Obj=0x7ffdeb886450
TDerived destroyed
main: o1=0 &o1=0x7ffdeb886450
test: Obj=0

main: o2=0x55a5eb5e8e70 &o2=0x7ffdeb886458
FreeAndNil: Obj=0x55a5eb5e8e70 &Obj=0x7ffdeb886470
TDerived destroyed
main: o2=0x55a5eb5e8e70 &o2=0x7ffdeb886458
test: Obj=0x55a5eb5e8e70

main: o3=0x55a5eb5e8e70 &o3=0x7ffdeb886460
FreeAndNil: Obj=0x55a5eb5e8e70 &Obj=0x7ffdeb886470
TDerived destroyed
main: o3=0x55a5eb5e8e70 &o3=0x7ffdeb886460
test: Obj=0x55a5eb5e8e70

main: o4=0x55a5eb5e8e70 &o4=0x7ffdeb886468
FreeAndNil: Obj=0x55a5eb5e8e70 &Obj=0x7ffdeb886470
TDerived destroyed
main: o4=0x55a5eb5e8e70 &o4=0x7ffdeb886468
test: Obj=0x55a5eb5e8e70

FreeAndNil: Obj=0 &Obj=0x7ffdeb886470