From: musiphil@bawi.org   
      
   On 2012-10-29 13:25, James K. Lowden wrote:   
   > On Sat, 27 Oct 2012 01:34:52 CST   
   > Seungbeom Kim wrote:   
   >   
   >>> I suppose if you had something like:   
   >>> union {   
   >>> uint32_t a;   
   >>> uint8_t b;   
   >>> } u;   
   >>>   
   >>> The compiler could be free to put b at any of the 4 bytes.   
   >>   
   >> No, both u.a and u.b should be at the beginning of u, [...].   
   >   
   > Am I reading the C++11 standard too strictly? 9.5 also says,   
   >   
   > "In a union, at most one of the non-static data members can be   
   > active at any time, that is, the value of at most one of the   
   > non-static data members can be stored in a union at any time."   
   >   
   > On one hand, the standard assures us the elements in a union all have   
   > the same starting address. On the other hand, it says only one can be   
   > active at a time, which tells me I can't read a member unless that   
   > member is the one most recently written to.   
      
   I don't see where your confusion comes from; the fact that all members   
   are located at the same address does not contradict but in fact *ensures*   
   that only one member is active at a time, because every member overlaps   
   with one another and writing to one "invalidates" all the others.   
   For example, even in the following case:   
      
    union {   
    uint32_t a;   
    uint8_t b;   
    uint8_t c;   
    } u;   
      
   u.b and u.c cannot live side-by-side and be active at a time because   
   they are required to start at the same address.   
      
   --   
   Seungbeom Kim   
      
      
    [ 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)   
|