home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,380 of 33,346   
   Matthias Hofmann to Seungbeom Kim   
   Re: Casting from void*   
   01 Jul 11 17:11:49   
   
   From: hofmann@anvil-soft.com   
      
   "Seungbeom Kim"  schrieb im Newsbeitrag   
   news:iudq83$9hm$1@usenet.stanford.edu...   
      
   > It seems that you have something like this in mind:   
   >   
   >    struct X { ... };   
   >    struct Y { ... };   
   >    struct Z : X, Y { ... };   
   >   
   >    Y* py = new Z;   
   >    void* pv = dynamic_cast(py);   
   >    assert(pv != py);   
   >    assert(pv == dynamic_cast(py));   
      
   You are relying on a certain memory layout of the X and Y subobjects within   
   Z. For your example, a compiler is likely to structure a Z object like this:   
      
   [Storage for X's data]   
   [Storage for Y's data]   
   [Storage for Z's data]   
      
   Let's see what this means for the casts in your example. The first line of   
   code makes a pointer-to-Y point to a new Z object:   
      
   [Storage for X's data]   
   [Storage for Y's data] <- py   
   [Storage for Z's data]   
      
   The second line performs a dynamic_cast from pointer-to-Y to   
   pointer-to-void, which yields the address of the complete object:   
      
   [Storage for X's data] <- pv   
   [Storage for Y's data] <- py   
   [Storage for Z's data]   
      
   For this reason, pv and py do not compare equal indeed in the third line.   
   The dynamic_cast from pointer-to-Y to pointer-to-X in the fourth line yields   
   the address of the X subobject within Z, which does indeed compare equal to   
   pv.   
      
   However, as far as I know, there is no requirement for a compiler to use the   
   layout shown above. If the positions of the areas of storage for the X and Y   
   subobjects are switched, both asserts will fail.   
      
   --   
   Matthias Hofmann   
   Anvil-Soft, CEO   
   http://www.anvil-soft.com - The Creators of Toilet Tycoon   
   http://www.anvil-soft.de - Die Macher des Klomanagers   
      
      
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca