23fd04ae   
   From: thomasmang.ng@gmail.com   
      
   Am 04.04.2012 19:21, schrieb goran.pusic@gmail.com:   
      
   > However, what you want is a variable-element-number array, and people are   
   doing it on various implementations.   
   > In fact, you might oftentimes see std::string implemented like that (only   
   one buffer for all data, chars included + copy-on-write).   
   >   
   > Here's an implementation that might work.   
   >   
   > template   
   > struct vararr   
   > {   
   > const size_t len;   
   > t data[1];   
   >   
   > static vararr* create(size_t s) { return new (s) vararr(s); }   
   >   
   > ~vararr() { std::for_each(p1(), p1()+(len-1),&destruct); }   
   >   
   > void operator delete(void* p, size_t cElems) { delete [] sta   
   ic_cast(p); }   
   >   
   > private:   
   >   
   > t* p1() { return&data[1]; }   
      
   that kills it in the general case (i.e. without specific implementation   
   knowledge). Your code is dereferencing beyond array bounds. One could use   
   something like   
   t* p1() { return data + 1; }   
   or   
   t* p1() { return &data[0] + 1; }   
      
   but only subject to never incrementing that pointer again as it's located   
   already at the last possible valid position (data is still only an array of   
   size one; the fact that in terms of memory outline it could also be an array   
   of size len does, I am    
   afraid, not help regarding the pointer arithemtic rules of 5.7/5). Hence your   
   constructor code is invalid.   
   Moreover, your constructor code might overwrite memory used by vararr itself   
   (though only used for alignment purposes and being garbage bytes, officially   
   it would belong to foo and overwriting it would, I strongly suppose, trigger   
   UB).   
      
   Don't get me wrong; there are various ways getting it done and which do work   
   from a practical point of view; the question is if it can be made guaranteed   
   to be working.   
      
      
      
      
      
      
   --   
    [ 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)   
|