From 8670823119300430649 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f78e5,855073145fb9fdb7 X-Google-Attributes: gidf78e5,public From: ncm@nospam.cantrip.org (Nathan Myers) Subject: Re: Minimum Size of Array in Standard (solution) Date: 1998/11/12 Message-ID: <72e9ql$mgp$1@shell7.ba.best.com>#1/1 X-Deja-AN: 411159770 Approved: stephen.clamage@sun.com (comp.std.c++) References: <199811032027.NAA25799@ncar.ucar.EDU> <72a0m6$o75$1@news.lth.se> <72ak12$ma2$1@shell7.ba.best.com> <72c1m9$ikm$1@news.lth.se> Organization: http://www.cantrip.org/ X-UID: 0000000001 X-Status: $$$T Newsgroups: comp.std.c++ Originator: clamage@taumet Hans Olsson wrote: >Nathan Myers wrote: >>Hans Olsson wrote: >>>Nathan Myers wrote: >>>>There is a standard-conforming way to get a similar effect. >>>> >>>> template >>>> struct varstruct >>>> { >>>> union { >>>> unsigned int num_elements; >>>> T dummy[(sizeof(unsigned int)+sizeof(T)-1)/sizeof(T)]; >>>> }; >>>> T* elements() { return (T*)(char*)(this+1); } >>>> }; >>>> >>>>The dummy array ensures that (this+1) is aligned properly for a T. >>> >>> why not plain T dummy ? >> >>Because a single T might not be big enough. > >I understand that T might be smaller than unsigned int, but >I fail to see the problem. > >A union cannot contain padding before its members (can it? would it >matter?). Since (this+1) is suitably aligned for an object of the >union (or arrays of unions wouldn't work) it must thus also be suitably >aligned for an object of type T. Maybe Hans is right. I think a union cannot contain padding before its first member, at least. Then this >>>> union { >>>> T dummy; >>>> unsigned int num_elements; >>>> }; would be sufficient. >>>Why not have a template-union instead of hiding the union inside >>>a struct? >> >>The point is that the varstruct probably has useful things in it. > >But I though those other items should also be inside the union >(preferably in a struct): > >struct header {...} >template union varunion { > struct header; > T dummy; > T* elements() {return (T*)(char*)(this+1);} >}; >varunion* x = > (varunion*) operator new(sizeof(varunion)+sizeof(T)*n); This is close to what I meant. That a single T is enough is a useful insight. -- Nathan Myers ncm@nospam.cantrip.org http://www.cantrip.org/ [ comp.std.c++ is moderated. To submit articles, try just posting with ] [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ] [ --- Please see the FAQ before posting. --- ] [ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]