Advertisement
homer512

pointer cast costs

Jun 19th, 2017
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. /**
  2.  * Nonempty base class
  3.  */
  4. struct Base
  5. {
  6.   int v;
  7.  
  8.   void do_something();
  9.  
  10.   static void do_something(Base* self);
  11. };
  12.  
  13. /**
  14.  * Child class that introduces a vtable pointer
  15.  *
  16.  * The combination of nonempty base and vtable in child causes an offset
  17.  * between pointers to Base and pointers to Child.
  18.  *
  19.  * Example:
  20.  * Child* child = NOT NULL;
  21.  * Base* base = child;
  22.  * reinterpret_cast<intptr_t>(child) != reinterpret_cast<intptr_t>(base);
  23.  */
  24. struct Child: Base
  25. {
  26.   virtual ~Child() = default;
  27.  
  28.   Base* self_as_base();
  29. };
  30.  
  31. /**
  32.  * Unconditional conversion because `this` must not be NULL
  33.  */
  34. Base* Child::self_as_base()
  35. { return this; }
  36.  
  37. /**
  38.  * Conditional conversion because child may be NULL
  39.  */
  40. Base* child_to_base_ptr(Child* child)
  41. {
  42.   return child;
  43. }
  44. /**
  45.  * Unconditional conversion because references must not be NULL
  46.  */
  47. Base& child_to_base_ref(Child& child)
  48. {
  49.   return child;
  50. }
  51. /**
  52.  * Unconditional conversion because `this` must not be NULL
  53.  */
  54. void call_do_something(Child** children, int count)
  55. {
  56.   for(int i = 0; i < count; ++i)
  57.     children[i]->do_something();
  58. }
  59. /**
  60.  * Conditional conversion because child may be NULL
  61.  */
  62. void call_do_something_static_ptr(Child** children, int count)
  63. {
  64.   for(int i = 0; i < count; ++i)
  65.     Base::do_something(children[i]);
  66. }
  67. /**
  68.  * Unconditional conversion because references must not be NULL
  69.  */
  70. void call_do_something_static_ref(Child** children, int count)
  71. {
  72.   for(int i = 0; i < count; ++i)
  73.     Base::do_something(&static_cast<Base&>(*children[i]));
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement