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 32,476 of 33,346   
   Seungbeom Kim to All   
   Re: Is it ever unsafe to realloc?   
   12 Jul 12 16:20:17   
   
   From: musiphil@bawi.org   
      
   On 2012-07-12 13:08, fmatthew5876 wrote:   
   >   
   > By why do copy/move constructors have to always be called?   
      
   Because they are supposed to know the class invariants and maintain them.   
   With just bit-copying, the class doesn't have a chance to maintain the   
   invariants. Others in this thread have given examples involving pointers.   
      
   And I didn't say "always": if you have a struct { int x, y; }, it's   
   safe to bit-copy, i.e. without any copy/move constructor involved.   
   It's safe even if the struct contains pointers, as long as they don't   
   point somewhere inside itself, because they don't need to be adjusted.   
   But if the class has a user-defined copy/move constructor, it has one   
   because it needs one, and copying/moving should be its job.   
      
   > Can some   
   > objects maintain internal pointers to parts of themselves in vtables?   
   > For instance with virtual functions and/or virtual inheritance?   
      
   No. Vtables are per-class, and they can't contain per-object data.   
      
   >   
   > For instance when would this be unsafe?   
   >   
   > class A {   
   > //stuff   
   > };   
   >   
   > A* ptr = (A*)malloc(sizeof(A)*2);   
   > new (ptr) A();   
   > new (ptr+1) A();   
   >   
   > ptr = (A*) realloc(ptr, sizeof(A) * 3);   
   > new (ptr+2) A();   
   >   
   > ptr[0].~A();   
   > ptr[1].~A();   
   > ptr[2].~A();   
   > free(ptr);   
   >   
   > or this?   
   >   
   > A* ptr1 = (A*)malloc(sizeof(A));   
   > A* ptr2 = (A*)malloc(sizeof(A));   
   >   
   > new (ptr1) A();   
   > memcpy(ptr2, ptr1, sizeof(A));   
   >   
   > ptr2.~A():   
   > free(ptr1);   
   > free(ptr2);   
      
   Both cases are unsafe if A is not POD.   
      
   --   
   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)   

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


(c) 1994,  bbs@darkrealms.ca