Topic: Question about delete


Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1999/08/07
Raw View
Hyman Rosen wrote:
>
> James Kuyper <kuyper@wizard.net> writes:
> > So the question is, should C++ follow suit in standardizing existing
> > practice like this? Disclaimer: I've never used the hack, though I've
> > worked on code that did.
>
> Sure. Two added restrictions should be sufficient - the type of the
> extensible array should be POD, and such a class cannot be derived
> from. There is also a question of using 'new' with such structures -
> should there be a way to pass the array size, or should allocation
> be restricted to malloc?

You can solve this problem by allowing to create complete types
from the incomplete type using a special syntax, f.ex. if you
have

struct C9x_string
{
  int length;
  char data[];
};

then you could define

C9x_string[[5]]

as complete type which is generated by inserting "5" as array
length. For static variables, the number would have to be a
constant expression, but for automatic and dynamic variables,
arbitrary expressions of type size_t would be allowed.

Example:

C9x_string bar[[20]] = { 5, "x" }; // global variable

C9x_string baz[[]] = { 5, "Hello world!" };
                             // should this be allowed?

void foo(int n)
{
  C9x_string foobar[[2*n+1]]; // automatic variable with dynamic size
  C9x_string p = &foobar; // pointers to the incomplete type can
                          // point to any complete type generated
                          // from it
  p = new C9x_string[[4*n]]; // heap variable with dynamic size
}

You could even define assignment of complete types:

void foo(int n1, int n2)
{
  C9x_string s1[[n1]];
  C9x_string s2[[n2]];

  s1 = s2;
  // all "normal" fields are copies normally
  // for the array, min(n1, n2) fields are copied
  // if n1>n2, then s1.data[n2] to s1.data[n1-1] are
  //   default initialized (i.e. for char, they are
  //   just uninitialized)

  C9x_string* p = new C9x_string[[7]];

  s1 = *p; // Error: *p is incomplete
  *p = s1; // Error: *p is incomplete
}

The last two cannot compile since the compiler cannot know
the size (actually it could determine it here, but it's not
possible generally).
---
[ 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              ]





Author: jcoffin@taeus.com (Jerry Coffin)
Date: 1999/07/26
Raw View
In article <378D39D7.B7BB00D@acm.org>, petebecker@acm.org says...

[ .... ]

> > I see what look to me like bigger hurdles.  First, a normal type
> > becomes complete when you finish defining it, where these don't really
> > become complete until you actually create them.  Second, it looks like
> > objects of this type have to be created dynamically.  Third, dealing
> > with things like assignment could be tricky -- perhaps two objects
> > should only be considered assignment-compatible (at least via the
> > built-in assignment operator) if the VLA's are the same size.
>
> That amounts to an awful lot of work to go through for very little
> benefit.

I'm not sure how much work it really is -- most of these apply (at
least to some degree) to a C compiler as well.  Given that most C++
vendors also sell C compilers, they're probably going to be
implementing all of it (in whatever form the C standard requires)
anyway.  As long as the C++ standard treats them similarly to the C
standard, it's less a question of how much work it is to implement
than of how much work it is to make it work in both compilers.  I'm
sure you know more about that than I do, but I would have guessed that
the vast majority of code for the C compiler would normally be re-used
in the same vendor's C++ compiler, so it would often happen almost by
accident.  In fact, I can see where in some cases, it might require a
little bit of extra work (admittedly likely to be a trivial amount) to
KEEP it from happening when it got implemented in the C compiler.
---
[ 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              ]





Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1999/07/29
Raw View
Andrei Alexandrescu wrote:
>
> In article <3784853F.61CB223E@acm.org>,
>   Pete Becker <petebecker@acm.org> wrote:
> > At the very least, if this hack is to become part of C++,
> there
> > has to be a rule, enforced by the compiler, that prohibits deriving
> from
> > these things.
>
> I bet in this case the first and most used idiom for this hack would be
> to create final classes, e.g.:
>
> class FinalClass // not intended to be derived from
> {
>     ...
>     char unused[];
> };

I think it could also be used to force alignment more
easily:

template<class T, size_t size> struct Memory
{
  unsigned char mem[size];
  T aligned[];
};

This would guarantee that Memory<T> is always correctly
aligned for T, without really having a member of T
(sizeof(Memory<T>) could even be less than sizeof(T)).


[ 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              ]






Author: Pete Becker <petebecker@acm.org>
Date: 1999/07/15
Raw View
Jerry Coffin wrote:
>
> > So I think it would be better to simply prevent deriving from
> > such things, as Pete Becker suggested.
>
> I think the use of the virtual keyword as I suggested answers these
> objections.
>
> I see what look to me like bigger hurdles.  First, a normal type
> becomes complete when you finish defining it, where these don't really
> become complete until you actually create them.  Second, it looks like
> objects of this type have to be created dynamically.  Third, dealing
> with things like assignment could be tricky -- perhaps two objects
> should only be considered assignment-compatible (at least via the
> built-in assignment operator) if the VLA's are the same size.

That amounts to an awful lot of work to go through for very little
benefit.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com
---
[ 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              ]





Author: dHarrison@worldnet.att.net (Doug Harrison)
Date: 1999/07/15
Raw View
Nathan Myers wrote:

>The struct hack is obsolete (as well as undefined) if you're
>writing C++ code.  The well-defined idiom to use in its place is
>
>  mytype* array() { return (mytype*)(this+1); }
>
>If you want to be more scrupulous, use
>
>  mytype* array()
>    { return static_cast<mytype*>(static_cast<void*>(this+1)); }
>
>You can dress it up a bit:
>
>  mytype& array(std::size_t i)
>  {
>      if (i > this->array_size) throw std::length_error();
>      return (static_cast<mytype*>(static_cast<void*>(this+1)))[i];
>  }

It seems to me that:

 struct X
 {
    // ...
   int a[];
 };

is altogether superior to the well-defined idiom. The compiler I use most
has supported this syntax for several versions now, and the few times I've
used it, I've appreciated it. Deriving from X or including X as a non-static
member of another class is problematic, and the compiler can detect and warn
about such attempts. Then there are the alignment issues. Also, this
approach doesn't require casts, which is always nice.

--
Doug Harrison
dHarrison@worldnet.att.net
---
[ 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              ]





Author: ncm@nospam.cantrip.org (Nathan Myers)
Date: 1999/07/15
Raw View
<James.Kanze@dresdner-bank.com> wrote:
>  ncm@nospam.cantrip.org (Nathan Myers) wrote:
>> <blargg@flash.net> wrote:
>> > James Kuyper <kuyper@wizard.net> wrote:
>> >
>> >[struct hack - variable-sized array of T at end of struct]
>>
>> The struct hack is obsolete (as well as undefined) if you're
>> writing C++ code.  The well-defined idiom to use in its place is
>>
>>   mytype* array() { return (mytype*)(this+1); }
>
>Which, of course, fails if mytype has stronger alignment requirements
>than the type of this.  I've used it when mytype was char, but using it
>when mytype is a template argument can only be considered an error, and
>using it when mytype is anything other than char is probably an
>invitation to maintenance problems.

James is correct; the above must be taken as shorthand for
something potentially much messier, or non-portable, in the
general case.

--
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              ]





Author: James.Kanze@dresdner-bank.com
Date: 1999/07/15
Raw View
In article <7mjvjr$ui$1@shell7.ba.best.com>,
  ncm@nospam.cantrip.org (Nathan Myers) wrote:
> <James.Kanze@dresdner-bank.com> wrote:
> >  ncm@nospam.cantrip.org (Nathan Myers) wrote:
> >> <blargg@flash.net> wrote:
> >> > James Kuyper <kuyper@wizard.net> wrote:
> >> >
> >> >[struct hack - variable-sized array of T at end of struct]
> >>
> >> The struct hack is obsolete (as well as undefined) if you're
> >> writing C++ code.  The well-defined idiom to use in its place is
> >>
> >>   mytype* array() { return (mytype*)(this+1); }
> >
> >Which, of course, fails if mytype has stronger alignment requirements
> >than the type of this.  I've used it when mytype was char, but using it
> >when mytype is a template argument can only be considered an error, and
> >using it when mytype is anything other than char is probably an
> >invitation to maintenance problems.
>
> James is correct; the above must be taken as shorthand for
> something potentially much messier, or non-portable, in the
> general case.

But it sure is tempting :-).

BTW: I originally suggested something like this myself many years back.
It was Steve Clamage who originally pointed out the potential alignment
problem.

--
James Kanze                         mailto:
James.Kanze@dresdner-bank.com
Conseils en informatique orient   e objet/
                        Beratung in objekt orientierter
Datenverarbeitung
Ziegelh   ttenweg 17a, 60598 Frankfurt, Germany  Tel. +49 (069) 63 19 86
27


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.


[ 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              ]






Author: ncm@nospam.cantrip.org (Nathan Myers)
Date: 1999/07/11
Raw View
<blargg@flash.net> wrote:
> James Kuyper <kuyper@wizard.net> wrote:
>
>[struct hack - variable-sized array of T at end of struct]
>
>> The struct hack has a long history - it has usually been done using
>>
>>         mytype array[1];

The struct hack is obsolete (as well as undefined) if you're
writing C++ code.  The well-defined idiom to use in its place is

  mytype* array() { return (mytype*)(this+1); }

If you want to be more scrupulous, use

  mytype* array()
    { return static_cast<mytype*>(static_cast<void*>(this+1)); }

You can dress it up a bit:

  mytype& array(std::size_t i)
  {
      if (i > this->array_size) throw std::length_error();
      return (static_cast<mytype*>(static_cast<void*>(this+1)))[i];
  }

--
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              ]






Author: fjh@cs.mu.OZ.AU (Fergus Henderson)
Date: 1999/07/12
Raw View
jcoffin@taeus.com (Jerry Coffin) writes:

 >petebecker@acm.org says...
 >
 >> At the very least, if this hack is to become part of C++, there
 >> has to be a rule, enforced by the compiler, that prohibits deriving from
 >> these things.
 >
 >I'm not sure this is true -- as long as the compiler ensures that the
 >variable-sized array is always at the end of the object, derivation
 >shouldn't be a problem.  The obvious way to do this would be to put
 >the actual offset of the variable-sized array in a vtable-like item
 >(or even in the actual vtable).

In some ways that's a nice idea, but it would be less efficient
in cases where derivation was not required, and it would also break
binary compatibility with traditional implementations of variable-sized
arrays.  So I think it would be better to simply prevent deriving from
such things, as Pete Becker suggested.

--
Fergus Henderson <fjh@cs.mu.oz.au>  |  "I have always known that the pursuit
WWW: <http://www.cs.mu.oz.au/~fjh>  |  of excellence is a lethal habit"
PGP: finger fjh@128.250.37.3        |     -- the last words of T. S. Garp.


[ 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              ]






Author: James.Kanze@dresdner-bank.com
Date: 1999/07/13
Raw View
In article <7m3qt7$96t$1@panix.com>,
  comeau@comeaucomputing.com wrote:
> In article <t7yagrrkmv.fsf@calumny.jyacc.com> Hyman Rosen
<hymie@prolifics.com> writes:
> >James Kuyper <kuyper@wizard.net> writes:

> >> So the question is, should C++ follow suit in standardizing
> >> existing practice like this? Disclaimer: I've never used the hack,
> >> though I've worked on code that did.

> >Sure. Two added restrictions should be sufficient - the type of the
> >extensible array should be POD, and such a class cannot be derived
> >from.

> Restrictions over the C9X ones that is.  There might need to be more
> (including in C9X).

Globally, I think that this poses less problems (and requires less
restrictions) than variable length arrays.  Whatever you think of the
struct hack, variable length arrays are definitly useful in C, and once
you have variable length arrays, you've done most of the work for the
struct hack.

Of course, in C++, variable length arrays aren't nearly as important as
they are in C.

--
James Kanze                         mailto:
James.Kanze@dresdner-bank.com
Conseils en informatique orient   e objet/
                        Beratung in objekt orientierter
Datenverarbeitung
Ziegelh   ttenweg 17a, 60598 Frankfurt, Germany  Tel. +49 (069) 63 19 86
27


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.


[ 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              ]






Author: James.Kanze@dresdner-bank.com
Date: 1999/07/14
Raw View
In article <7ltiej$sfj$1@panix.com>,
  comeau@comeaucomputing.com wrote:
>
> In article <378016C9.C947149F@acm.org> Pete Becker
<petebecker@acm.org> writes:
> >James Kuyper wrote:

> >> In C9X, they are finally standardizing the traditional "struct
> >> hack", whereby a short array at the end of a struct is indexed
> >> beyond it's nominal lenght to access memory allocated beyond the
> >> nominal size of the struct. 'char[] text;' is precisely the sytax
> >> that they are legalizing for doing this. I'd recommend that as soon
> >> at C9X is approved, someone should start thinking through the
> >> implications for adopting that construct into C++.

> I clearly see the temptation to allow this facility of "flexible array
> members" to C9X but IMO it is a narrow-minded hack.  I certainly hope
> that the C++ committee does not adopt it.

> >> Obviously, it's not as necessary in C++, where we have vector<> or
> >> string or valarray<> to serve the same purpose in a safer fashion.

> For sure.  There are even alternatives, some would say superior, in C.

> >>However, should it at least be made legal, for compatibility with
> >>C9X? Obviously, such a struct could only usefully be created using
> >>placement new, or malloc() for POD structs.

> >There's a major problem with allowing this in C++: it produces a type
> >that cannot be derived from.

> You don't even need to look that far.  As I recall the feature, I
> don't even think you would always be able to assign it to something
> else in C++ (I could have this wrong).

How does C define assignment of such structures?

--
James Kanze                         mailto:
James.Kanze@dresdner-bank.com
Conseils en informatique orient=E9e objet/
                        Beratung in objekt orientierter
Datenverarbeitung
Ziegelh=FCttenweg 17a, 60598 Frankfurt, Germany  Tel. +49 (069) 63 19 86
27


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
---
[ 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              ]





Author: James.Kanze@dresdner-bank.com
Date: 1999/07/15
Raw View
In article <7m8cks$3a5$1@shell7.ba.best.com>,
  ncm@nospam.cantrip.org (Nathan Myers) wrote:
>
> <blargg@flash.net> wrote:
> > James Kuyper <kuyper@wizard.net> wrote:
> >
> >[struct hack - variable-sized array of T at end of struct]
> >
> >> The struct hack has a long history - it has usually been done using
> >>
> >>         mytype array[1];
>
> The struct hack is obsolete (as well as undefined) if you're
> writing C++ code.  The well-defined idiom to use in its place is
>
>   mytype* array() { return (mytype*)(this+1); }

Which, of course, fails if mytype has stronger alignment requirements
than the type of this.  I've used it when mytype was char, but using it
when mytype is a template argument can only be considered an error, and
using it when mytype is anything other than char is probably an
invitation to maintenance problems.

--
James Kanze                         mailto:
James.Kanze@dresdner-bank.com
Conseils en informatique orient=E9e objet/
                        Beratung in objekt orientierter
Datenverarbeitung
Ziegelh=FCttenweg 17a, 60598 Frankfurt, Germany  Tel. +49 (069) 63 19 86
27


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
---
[ 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              ]





Author: jcoffin@taeus.com (Jerry Coffin)
Date: 1999/07/15
Raw View
In article <7md604$bpg$1@mulga.cs.mu.OZ.AU>, fjh@cs.mu.OZ.AU says...

[ derivation from structs including variable-sized arrays ]

>  >I'm not sure this is true -- as long as the compiler ensures that the
>  >variable-sized array is always at the end of the object, derivation
>  >shouldn't be a problem.  The obvious way to do this would be to put
>  >the actual offset of the variable-sized array in a vtable-like item
>  >(or even in the actual vtable).
>
> In some ways that's a nice idea, but it would be less efficient
> in cases where derivation was not required,

If it used the virtual keyword as I suggested, to differentiate
between those that would allow derivation and those that wouldn't,
you'd only have to pay when you used the feature.

> and it would also break binary compatibility with traditional
> implementations of variable-sized arrays.

If the virtual keyword was used as I suggested, I don't see a problem
arising.  The typical situation would be linking together some C and
C++ code, both of which use the variable-sized array.  The typical
situation would be to use a C header to tell the C++ compiler what the
struct looked like.  Since the header wouldn't mark it as "virtual",
the compiler would use the traditional method of implementation and
prevent derivation from the struct.

> So I think it would be better to simply prevent deriving from
> such things, as Pete Becker suggested.

I think the use of the virtual keyword as I suggested answers these
objections.

I see what look to me like bigger hurdles.  First, a normal type
becomes complete when you finish defining it, where these don't really
become complete until you actually create them.  Second, it looks like
objects of this type have to be created dynamically.  Third, dealing
with things like assignment could be tricky -- perhaps two objects
should only be considered assignment-compatible (at least via the
built-in assignment operator) if the VLA's are the same size.

Of course in a few situations, the second could be seen as an
advantage.  E.g. people who use `delete this' would often like a way
of ensuring that an object only be created dynamically.  Of course,
some people would point out that anything that encourages use of
`delete this' can't be a good thing either.

These objections, however, seem to apply regardless of whether you
allow derivation from the struct/class containing the VLA.
---
[ 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              ]





Author: Pete Becker <petebecker@acm.org>
Date: 1999/07/08
Raw View
Ken Hagan wrote:
>
> I wouldn't call this a major problem. There are already ways of
> creating classes that you can't derive from, and we seem to survive.
>

I'm not willing to dismiss this so lightly. If you derive from one of
these, the data members in your derived class will be mysteriously
overwritten by assignments in the base. This is not a good thing, and
there is no normal programming practice in C++ that does anything
similar. At the very least, if this hack is to become part of C++, there
has to be a rule, enforced by the compiler, that prohibits deriving from
these things.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com


[ 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              ]






Author: James Kuyper <kuyper@wizard.net>
Date: 1999/07/08
Raw View
blargg@flash.net wrote:
>
> In article <377F65AE.5DCAEE74@wizard.net>, James Kuyper
> <kuyper@wizard.net> wrote:
>
> [snip]
>
> [ struct X {
>     int size;
>     char data [];
> };]
>
> > In C9X, they are finally standardizing the traditional "struct hack",
> > whereby a short array at the end of a struct is indexed beyond it's
> > nominal lenght to access memory allocated beyond the nominal size of the
> > struct. 'char[] text;' is precisely the sytax that they are legalizing
> > for doing this. I'd recommend that as soon at C9X is approved, someone
> > should start thinking through the implications for adopting that
> > construct into C++. Obviously, it's not as necessary in C++, where we
> > have vector<> or string or valarray<> to serve the same purpose in a
> > safer fashion.
>
> Huh? I figure the purpose of this "hack" is to reduce the number of
> freestore allocations by one, i.e. allocate the variable number of
> elements along with the extra information. I suppose it also has the
> effect of making it simpler to access it all directly in C too, which is
> the point you're addressing.

Both purposes are relevant. Keeping the structure's contents in the same
block of memory as the array for caching purposes was also a motive, and
one that the vector<>, string, or valarray<> solutions don't address.

> > However, should it at least be made legal, for
> > compatibility with C9X? Obviously, such a struct could only usefully be
> > created using placement new, or malloc() for POD structs.
>
> <sarcasm>
> Maybe we could add a new syntax
>
>     new X.data [99];
>
> Wow, and it wouldn't break any current programs!
> </sarcasm>

The struct hack has a long history - it has usually been done using

 mytype array[1];

In that form, it works on most implementations of C, and is almost as
old as C, even though it wasn't standard. There are current compilers
which allow you to do it using (as an extension, of course)

 mytype array[0];

The C9X innovation was to give official blessing to the syntax:

 mytype array[];

That syntax shares with the [0] option the advantage over [1] that it
would have been an error in C89 code. Also, it allows you to tell that
the struct hack will be being used just by looking at the structure
declaration - in the traditional method, you could only tell by looking
at the code that used the structure (or at it's documentation, if any).

So the question is, should C++ follow suit in standardizing existing
practice like this? Disclaimer: I've never used the hack, though I've
worked on code that did.


[ 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              ]






Author: "Ken Hagan" <K.Hagan@thermoteknix.co.uk>
Date: 1999/07/09
Raw View
Greg Comeau wrote in message <7lvnci$j1u$1@panix.com>...
>Actually, Comeau C++ supports it for compatibility with MSVC++
>(we need to support MS features and bugs), but otherwise it is not
>recommended.

I'm not surprised. In my experience, a 1-element array at the end
of the structure is equally usable and the compiler doesn't whinge
about my using "non-standard extensions" (sic). However...

In the fullness of time (5 years?), will C++ under any pressure to
adopt wholesale the new features of C9X?

Do the C9X people accept "this is unlikely to be adopted in C++"
as a legitimate argument against a feature in C?

Perhaps both questions boil down to...

Have we now past the era of "as close as possible but no closer"?
---
[ 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              ]





Author: Andrei Alexandrescu <andrewalex@hotmail.com>
Date: 1999/07/09
Raw View
In article <3784853F.61CB223E@acm.org>,
  Pete Becker <petebecker@acm.org> wrote:
> At the very least, if this hack is to become part of C++,
there
> has to be a rule, enforced by the compiler, that prohibits deriving
from
> these things.

I bet in this case the first and most used idiom for this hack would be
to create final classes, e.g.:

class FinalClass // not intended to be derived from
{
    ...
    char unused[];
};

Given that the only current method for creating final classes is via the
virtual base hack, that would be an interesting alternative.

Of course, I would prefer a better way of doing this to both. The thing
is, now the only way of saying "don't inherit classes that are not meant
to be derived from" is via coding standards.

Andrei


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
---
[ 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              ]





Author: Hyman Rosen <hymie@prolifics.com>
Date: 1999/07/09
Raw View
James Kuyper <kuyper@wizard.net> writes:
> So the question is, should C++ follow suit in standardizing existing
> practice like this? Disclaimer: I've never used the hack, though I've
> worked on code that did.

Sure. Two added restrictions should be sufficient - the type of the
extensible array should be POD, and such a class cannot be derived
from. There is also a question of using 'new' with such structures -
should there be a way to pass the array size, or should allocation
be restricted to malloc?
---
[ 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              ]





Author: jcoffin@taeus.com (Jerry Coffin)
Date: 1999/07/09
Raw View
In article <3784853F.61CB223E@acm.org>, petebecker@acm.org says...

[ ... ]

> At the very least, if this hack is to become part of C++, there
> has to be a rule, enforced by the compiler, that prohibits deriving from
> these things.

I'm not sure this is true -- as long as the compiler ensures that the
variable-sized array is always at the end of the object, derivation
shouldn't be a problem.  The obvious way to do this would be to put
the actual offset of the variable-sized array in a vtable-like item
(or even in the actual vtable).  You might even want to allow using
the virtual keyword on it -- if it's not virtual, you'd use its static
offset in the struct/class, and no (further) derivation would be
allowed.  If you mark it as virtual, then it will always be stored at
the end of the struct/class, and its offset will be available in the
vtable.

Note that the first option (the non-virtual one) would cure what some
Java and Eiffel programmers see as a deficiency in C++ -- an
equivalent of "final" in Java, ensuring against further derivation.
---
[ 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              ]





Author: comeau@panix.com (Greg Comeau)
Date: 1999/07/09
Raw View
In article <newscache$spljef$w07$1@firewall.thermoteknix.co.uk> "Ken Hagan" <K.Hagan@thermoteknix.co.uk> writes:
>Greg Comeau wrote in message <7lvnci$j1u$1@panix.com>...
>>Actually, Comeau C++ supports it for compatibility with MSVC++
>>(we need to support MS features and bugs), but otherwise it is not
>>recommended.
>
>I'm not surprised. In my experience, a 1-element array at the end
>of the structure is equally usable and the compiler doesn't whinge
>about my using "non-standard extensions" (sic). However...

I think that you mean your current compiler and not "the compiler".

Certainly compilers can execute programs with undefined behavior
and stuff, but that doesn't change the issue of the behavior status.
This is exactly why C9X decided on the [] syntax, since it'll be
clear that a flexible array member is going to be your intention.

>In the fullness of time (5 years?), will C++ under any pressure to
>adopt wholesale the new features of C9X?

Pressure might not be the right word, but it'll certainly be an
issue at some point what to do in whole or in part.

>Do the C9X people accept "this is unlikely to be adopted in C++"
>as a legitimate argument against a feature in C?

I think that there is an implicit understanding from both committees
on this.  Some have already been literally "negotiated," others for
better or worse are deemed to be understood to only be important to
their repective committees and perhaps not the other's.  This is course
does not mean that it's the bottom line on the issues....

>Perhaps both questions boil down to...
>
>Have we now past the era of "as close as possible but no closer"?

C and C++ will always be leap-frogging and also going their seperate ways.

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***
---
[ 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              ]





Author: comeau@panix.com (Greg Comeau)
Date: 1999/07/09
Raw View
In article <t7yagrrkmv.fsf@calumny.jyacc.com> Hyman Rosen <hymie@prolifics.com> writes:
>James Kuyper <kuyper@wizard.net> writes:
>> So the question is, should C++ follow suit in standardizing existing
>> practice like this? Disclaimer: I've never used the hack, though I've
>> worked on code that did.
>
>Sure. Two added restrictions should be sufficient - the type of the
>extensible array should be POD, and such a class cannot be derived
>from.

Restrictions over the C9X ones that is.
There might need to be more (including in C9X).

>There is also a question of using 'new' with such structures -
>should there be a way to pass the array size, or should allocation
>be restricted to malloc?

I don't see how you could possible use new, since the type is
essentially a dynamic runtime template (yowza!) :), but I don't think
malloc is required since new char[X] is available too.
Unless of course you're talking about a new flexible array new.

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***
---
[ 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              ]





Author: Pete Becker <petebecker@acm.org>
Date: 1999/07/09
Raw View
Jerry Coffin wrote:
>
> In article <3784853F.61CB223E@acm.org>, petebecker@acm.org says...
>
> [ ... ]
>
> > At the very least, if this hack is to become part of C++, there
> > has to be a rule, enforced by the compiler, that prohibits deriving from
> > these things.
>
> I'm not sure this is true -- as long as the compiler ensures that the
> variable-sized array is always at the end of the object, derivation
> shouldn't be a problem.  The obvious way to do this would be to put
> the actual offset of the variable-sized array in a vtable-like item
> (or even in the actual vtable).

This doesn't work if you try to derive from two of these.

> You might even want to allow using
> the virtual keyword on it -- if it's not virtual, you'd use its static
> offset in the struct/class, and no (further) derivation would be
> allowed.  If you mark it as virtual, then it will always be stored at
> the end of the struct/class, and its offset will be available in the
> vtable.

This use of virtual seems like a rather elaborate mechanism to avoid
having to explicitly write a pointer and a malloc. I don't see what its
benefit is. Coding it explicitly is much more flexible.

>
> Note that the first option (the non-virtual one) would cure what some
> Java and Eiffel programmers see as a deficiency in C++ -- an
> equivalent of "final" in Java, ensuring against further derivation.

I don't see it. In order to use this mechanism to make a class "final"
you have to add a variable-sized array that you wouldn't otherwise have.
That's artificial at best.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com


[ 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              ]






Author: comeau@panix.com (Greg Comeau)
Date: 1999/07/09
Raw View
In article <MPG.11ee7f15e8520056989bfb@news.mindspring.com> jcoffin@taeus.com (Jerry Coffin) writes:
>In article <3784853F.61CB223E@acm.org>, petebecker@acm.org says...
>> At the very least, if this hack is to become part of C++, there
>> has to be a rule, enforced by the compiler, that prohibits deriving from
>> these things.
>
>I'm not sure this is true -- as long as the compiler ensures that the
>variable-sized array is always at the end of the object, derivation
>shouldn't be a problem.

Remember, even C9X has some constraints on flexible array members,
I'll call them FAMs from here on.  FAMs are not really a general purpose
facility but intended to solve a very focused pathological situation.

>The obvious way to do this would be to put
>the actual offset of the variable-sized array in a vtable-like item
>(or even in the actual vtable).

If I understand you, this would violate the premise of the hack, that
of having the "object" in one contiguous chunk.  Besides, for this to
work, some other C++ feature/rule would _have_ to be added/changed,
since the base class itself with the FAM would not be complete until
runtime!

>You might even want to allow using
>the virtual keyword on it -- if it's not virtual, you'd use its static
>offset in the struct/class, and no (further) derivation would be
>allowed.  If you mark it as virtual, then it will always be stored at
>the end of the struct/class, and its offset will be available in the
>vtable.
>
>Note that the first option (the non-virtual one) would cure what some
>Java and Eiffel programmers see as a deficiency in C++ -- an
>equivalent of "final" in Java, ensuring against further derivation.

Oh my.  Runtime types in C, bonus uses in C++. :)

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***


[ 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              ]






Author: blargg@flash.net
Date: 1999/07/10
Raw View
In article <3784DC61.8172B226@wizard.net>, James Kuyper
<kuyper@wizard.net> wrote:

[struct hack - variable-sized array of T at end of struct]

> The struct hack has a long history - it has usually been done using
>
>         mytype array[1];
>
> In that form, it works on most implementations of C, and is almost as
> old as C, even though it wasn't standard. There are current compilers
> which allow you to do it using (as an extension, of course)
>
>         mytype array[0];

How is this more useful?

So you can allocate like this?

    sizeof (type) + sizeof (mytype_type) * n

Why isn' the much-less error-prone offsetof() used?

    offsetof (type,array [n])

> The C9X innovation was to give official blessing to the syntax:
>
>         mytype array[];
>
> That syntax shares with the [0] option the advantage over [1] that it
> would have been an error in C89 code. Also, it allows you to tell that
> the struct hack will be being used just by looking at the structure
> declaration - in the traditional method, you could only tell by looking
> at the code that used the structure (or at it's documentation, if any).

Right. And it disables any compiler range checks on the array (I am
reminded of Andrew Koenig's article "How to write buggy programs", which
specifically mentions using the struct hack to prevent array range
checking compilers from being used :-)

> So the question is, should C++ follow suit in standardizing existing
> practice like this? Disclaimer: I've never used the hack, though I've
> worked on code that did.

It depends on how much it is used.

Doing a scan of my library code, I use it exclusively for memory
allocators (and debugging allocator adapters that catch overwrites and
protocol errors). This is the one place where you can't just "allocate the
variable portion in a separate memory block", for obvious reasons :-)

I have a preprocessor macro that I use for the array size, which can be
adjusted to suit the compiler. Maybe it's a very large value (if the
compiler range-checks), maybe 1, maybe 0, or maybe it's a preprocessor
macro that expands to nothing, or even something that renders the program
invalid, in the case that there is no way to use the struct hack on the
particular compiler. Obviously this macro renders a program that uses it
portable to only those compilers it was specifically defined for.

    #define VARIABLE_SIZED  // whatever compiler likes

    struct struct_hack {
        int size;
        char data [VARIABLE_SIZED];
    };

And, of course, as I mentioned before, I get the total size by using offsetof():

    srtuct_hack* const mem = static_cast<struct_hack*> (operator new
            ( offsetof (struct_hack,data [size]) ));
    mem->size = size;
    // ...
---
[ 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              ]





Author: jcoffin@taeus.com (Jerry Coffin)
Date: 1999/07/10
Raw View
In article <7m3rtu$am2$1@panix.com>, comeau@panix.com says...

[ ... ]

> >The obvious way to do this would be to put
> >the actual offset of the variable-sized array in a vtable-like item
> >(or even in the actual vtable).
>
> If I understand you, this would violate the premise of the hack, that
> of having the "object" in one contiguous chunk.

It would still be in one contiguous chunk -- instead of pointing from
the object to an allocation on the heap, the pointer would point to
somewhere inside the same object.  If the basic reason for including
this in C++ was to eliminate the extra storage for a pointer, this
obvious wouldn't help.  If, however, it was intended primarily to
reduce the number of allocations, it should do the job.  There's also
the fact that when it's in C, that might be a good reason to include
it in C++, even if it can't accomplish the other purposes for which it
was included in C (at least when used in a base class).

> Besides, for this to
> work, some other C++ feature/rule would _have_ to be added/changed,
> since the base class itself with the FAM would not be complete until
> runtime!

True -- and that's probably a trickier thing to deal with.

> >Note that the first option (the non-virtual one) would cure what some
> >Java and Eiffel programmers see as a deficiency in C++ -- an
> >equivalent of "final" in Java, ensuring against further derivation.
>
> Oh my.  Runtime types in C, bonus uses in C++. :)

I don't mean to insult anybody by saying so, but if it does happen
that way, it'll be a long ways from the only time things have been
done in rather roundabout ways in C++...


[ 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              ]






Author: clamage@eng.sun.com (Steve Clamage)
Date: 1999/07/10
Raw View
"Ken Hagan" <K.Hagan@thermoteknix.co.uk> writes:

>In the fullness of time (5 years?), will C++ under any pressure to
>adopt wholesale the new features of C9X?

>Do the C9X people accept "this is unlikely to be adopted in C++"
>as a legitimate argument against a feature in C?

The C++ Committee wants to keep C++ as compatible as possible with
C. One of its tasks will be to determine how to accomodate the C9X
changes, once a new C standard is official. Some C9X features will
require considerable study. For example, it is not clear that the
new complex types in C can be reconciled with the complex type in
the C++ library.

The C and C++ Committees have some membership in common, and also
have official liaison members to help maintain compatibility.  But
nothing prevents the C Committee from choosing to adopt language
features that could not reasonably be adopted in C++.  The C++
Committee is not obligated to bend C++ to meet such hypothetical
incompatibilties.

One would like to rely on good will in both committees, and indeed,
there is considerable good will on both sides. But in the end, the
committees are different and have different goals.

--
Steve Clamage, stephen.clamage@sun.com
---
[ 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              ]





Author: jcoffin@taeus.com (Jerry Coffin)
Date: 1999/07/10
Raw View
In article <3785DC69.7FFE3A21@acm.org>, petebecker@acm.org says...

[ ... ]

> > I'm not sure this is true -- as long as the compiler ensures that the
> > variable-sized array is always at the end of the object, derivation
> > shouldn't be a problem.  The obvious way to do this would be to put
> > the actual offset of the variable-sized array in a vtable-like item
> > (or even in the actual vtable).
>
> This doesn't work if you try to derive from two of these.

Yes and no -- you can no longer put them in the vtable; you have to
make them per-object instead.  Other than that, it seems to me as if
the basic concept would still work.

> This use of virtual seems like a rather elaborate mechanism to avoid
> having to explicitly write a pointer and a malloc. I don't see what its
> benefit is. Coding it explicitly is much more flexible.

Undoubtedly true.  I'm not trying to argue that this is necessarily a
particularly good idea.  It seemed to me that the previous arguments
broke down into two basic things 1) there are other ways to do this,
and 2) it renders derivation impossible.

I'm simply pointing out that it seems to me that from a purely
technical viewpoint, the latter is not entirely true -- it adds
difficulty to implementing inheritance, especially multiple
inheritance, but does not seem to preclude either one.

I'll openly admit that this doesn't give a final decision on the issue
as a whole.  It simply means that the question here is roughly
parallel to the one in C: it's not really a question of whether it CAN
be done, but only of whether it should be, based entirely on its own
merit (or lack thereof).  I'm not going to claim I have the ultimate
answer to that question -- I'm only saying that I'm pretty sure should
be the focus of the discussion.

> > Note that the first option (the non-virtual one) would cure what some
> > Java and Eiffel programmers see as a deficiency in C++ -- an
> > equivalent of "final" in Java, ensuring against further derivation.
>
> I don't see it. In order to use this mechanism to make a class "final"
> you have to add a variable-sized array that you wouldn't otherwise have.
> That's artificial at best.

That was really meant to be (at least partly) humorous.  Seriously
though, artificial as it might be, I'd consider it superior to the
method that's presently available.  In any case, if it were used that
way, it would be a long ways from the only thing that got done in
rather a roundabout, perhaps even counterintuitive, manner.
---
[ 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              ]





Author: Paul Lennon <plennon@kofax.com>
Date: 1999/07/03
Raw View
I was wondering whether delete will free all of the memory associated
with the following allocation.

struct Test
{
 DWORD number;
 char[] text;
};

char* pBytes = new char[100];
Test* pTest = reinterpret_cast< Test* >( pBytes );

....

delete pTest;

Thank you for your help.

Paul
---
[ 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              ]





Author: sbnaran@localhost.localdomain (Siemel Naran)
Date: 1999/07/04
Raw View
On 03 Jul 99 09:01:08 GMT, Paul Lennon <plennon@kofax.com> wrote:

>I was wondering whether delete will free all of the memory associated
>with the following allocation.
>
>struct Test
>{
> DWORD number;
> char[] text;
>};
>
>char* pBytes = new char[100];
>Test* pTest = reinterpret_cast< Test* >( pBytes );
>
>....
>
>delete pTest;

In some implementations, all the memory would be deleted.  In some
implementations, this is not so.

However, your program calls the wrong destructor Test::~Test(), and
hence your program is undefined.

And besides, the 100 chars won't be used for text.  Instead, the
first 4 (or something) bytes will be for the DWORD, and the second
4 (or something) will be for the pointer to an array of chars.
The actual array of chars won't be stored in the remaining 92 bytes.

One may do

struct Test
{
   std::string text;

   Test() { text.reserve(100); }
};

--
----------------------------------
Siemel B. Naran (sbnaran@uiuc.edu)
----------------------------------
---
[ 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              ]





Author: clamage@eng.sun.com (Steve Clamage)
Date: 1999/07/04
Raw View
Paul Lennon <plennon@kofax.com> writes:

>I was wondering whether delete will free all of the memory associated
>with the following allocation.

>struct Test
>{
> DWORD number;
> char[] text;
>};

>char* pBytes = new char[100];
>Test* pTest = reinterpret_cast< Test* >( pBytes );

>....

>delete pTest;

If the type of the pointer used to delete the memory via a
delete-expression is not the same as the type of the memory
allocated via a new-expression the results of the program
are undefined, with one exception: If you allocate a derived
class, you can delete via a pointer to a base pointer if the
base class has a virtual destructor.

Beyond that requirement, if you allocate with new[] and
deallocate with delete (instead of delete[]), or allocate
with new and deallocate with delete[] (instead of delete),
the results of the program are undefined.  (An implementation
or program might use different memory pools for new and new[].)

Reference for both requirements: 5.3.5 in the C++ standard.

You program fragment thus contains two instances of undefined
behavior, and you cannot assume it will work.

--
Steve Clamage, stephen.clamage@sun.com
---
[ 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              ]





Author: blargg@flash.net
Date: 1999/07/04
Raw View
In article <377CFBF7.748597EE@kofax.com>, Paul Lennon <plennon@kofax.com> wrote:

> I was wondering whether delete will free all of the memory associated
> with the following allocation.
>
> struct Test
> {
>         DWORD   number;
          ^^^^^
What is DWORD?

>         char[]  text;
          ^^^^^^
Not standard C++.

> };
>
> char*   pBytes  = new char[100];
> Test*   pTest   = reinterpret_cast< Test* >( pBytes );
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The storage that pBytes points to doesn't necessarily meet the alignment
requirement of Test, so this could be unspecified.

> ....
>
> delete pTest;

Undefined behavior - pTest is not a value that was the result of a
new-expression.

Answer: It can do anything.
---
[ 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              ]





Author: derobert@erols.com (Anthony DeRobertis)
Date: 1999/07/04
Raw View
In article <377CFBF7.748597EE@kofax.com>, Paul Lennon <plennon@kofax.com> wrote:

>I was wondering whether delete will free all of the memory associated
>with the following allocation.
>
>struct Test
>{
>        DWORD   number;
>        char[]  text;
>};
>
>char*   pBytes  = new char[100];
>Test*   pTest   = reinterpret_cast< Test* >( pBytes );
>
>....
>
>delete pTest;
>
>Thank you for your help.

You're lucky it does not crash. Array operator new must be matched by
array operator delete. You'd have to typecast it back, then use delete[].

And further, the above example should not compile -- "char[] text" is nonsence.

--
Windows 95 (win-DOH-z), n. A thirty-two bit extension and graphical
shell to a sixteen bit patch to an eight bit operating system
originally coded for a four bit microprocessor which was used in a PC
built by a two bit company that couldn't stand one bit of competition.
---
[ 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              ]





Author: James Kuyper <kuyper@wizard.net>
Date: 1999/07/05
Raw View
Anthony DeRobertis wrote:
ADR>
ADR> In article <377CFBF7.748597EE@kofax.com>, Paul Lennon <plennon@kofax.com> wrote:
ADR>
ADR> >I was wondering whether delete will free all of the memory associated
ADR> >with the following allocation.
ADR> >
ADR> >struct Test
ADR> >{
ADR> >        DWORD   number;
ADR> >        char[]  text;
ADR> >};
ADR> >
ADR> >char*   pBytes  = new char[100];
ADR> >Test*   pTest   = reinterpret_cast< Test* >( pBytes );
ADR> >
ADR> >....
ADR> >
ADR> >delete pTest;
ADR> >
ADR> >Thank you for your help.
ADR>
ADR> You're lucky it does not crash. Array operator new must be matched by
ADR> array operator delete. You'd have to typecast it back, then use delete[].
ADR>
ADR> And further, the above example should not compile -- "char[] text" is nonsence.

In C9X, they are finally standardizing the traditional "struct hack",
whereby a short array at the end of a struct is indexed beyond it's
nominal lenght to access memory allocated beyond the nominal size of the
struct. 'char[] text;' is precisely the sytax that they are legalizing
for doing this. I'd recommend that as soon at C9X is approved, someone
should start thinking through the implications for adopting that
construct into C++. Obviously, it's not as necessary in C++, where we
have vector<> or string or valarray<> to serve the same purpose in a
safer fashion. However, should it at least be made legal, for
compatibility with C9X? Obviously, such a struct could only usefully be
created using placement new, or malloc() for POD structs.
---
[ 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              ]





Author: Pete Becker <petebecker@acm.org>
Date: 1999/07/05
Raw View
James Kuyper wrote:
>
> In C9X, they are finally standardizing the traditional "struct hack",
> whereby a short array at the end of a struct is indexed beyond it's
> nominal lenght to access memory allocated beyond the nominal size of the
> struct. 'char[] text;' is precisely the sytax that they are legalizing
> for doing this. I'd recommend that as soon at C9X is approved, someone
> should start thinking through the implications for adopting that
> construct into C++. Obviously, it's not as necessary in C++, where we
> have vector<> or string or valarray<> to serve the same purpose in a
> safer fashion. However, should it at least be made legal, for
> compatibility with C9X? Obviously, such a struct could only usefully be
> created using placement new, or malloc() for POD structs.

There's a major problem with allowing this in C++: it produces a type
that cannot be derived from.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com
---
[ 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              ]





Author: nimel@my-deja.com
Date: 1999/07/05
Raw View
In article <377F65AE.5DCAEE74@wizard.net>,
  James Kuyper <kuyper@wizard.net> wrote:

> In C9X, they are finally standardizing the traditional "struct hack",
> whereby a short array at the end of a struct is indexed beyond it's
> nominal lenght to access memory allocated beyond the nominal size of
the
> struct. 'char[] text;' is precisely the sytax that they are legalizing
> for doing this.

Isn't this syntax somewhat odd? Wouldn't 'char text[]' be more natural?
No matter what the syntax is I don't think such constructs should be
part of the C++ language. As James Kuyper wrote, C++ already have
the standard library containers.

/Niklas Mellin



Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
---
[ 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              ]





Author: James Kuyper <kuyper@wizard.net>
Date: 1999/07/06
Raw View
nimel@my-deja.com wrote:
>
> In article <377F65AE.5DCAEE74@wizard.net>,
>   James Kuyper <kuyper@wizard.net> wrote:
>
> > In C9X, they are finally standardizing the traditional "struct hack",
> > whereby a short array at the end of a struct is indexed beyond it's
> > nominal lenght to access memory allocated beyond the nominal size of
> the
> > struct. 'char[] text;' is precisely the sytax that they are legalizing
> > for doing this.
>
> Isn't this syntax somewhat odd? Wouldn't 'char text[]' be more natural?
> No matter what the syntax is I don't think such constructs should be
> part of the C++ language. As James Kuyper wrote, C++ already have
> the standard library containers.

You're correct. I was just copying what the original poster wrote,
without noticing that problem :-{. The syntax that C9X will allow as the
last member of a struct containing at least two named members is "char
text[];".
---
[ 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              ]





Author: wmm@fastdial.net
Date: 1999/07/06
Raw View
In article <199907031555.KAA08148@ares.flash.net>,
  blargg@flash.net wrote:
> In article <377CFBF7.748597EE@kofax.com>, Paul Lennon
<plennon@kofax.com> wrote:
>
> > char*   pBytes  = new char[100];
> > Test*   pTest   = reinterpret_cast< Test* >( pBytes );
>                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> The storage that pBytes points to doesn't necessarily meet the
alignment
> requirement of Test, so this could be unspecified.

No, the alignment of the storage is guaranteed to be correct by the
Standard.  5.3.4p10 says,

 For arrays of char and unsigned char, the difference
 between the result of the new-expression and the address
 returned by the allocation function shall be an integral
 multiple of the most stringent alignment requirement (3.9)
 of any object type whose size is no greater than the size
 of the array being created.  [Note: Because allocation
 functions are assumed to return pointers to storage that is
 appropriately aligned for objects of any type, this
 constraint on array allocation overhead permits the common
 idiom of allocating character arrays into which objects of
 other types will later be placed.]
--
William M. Miller, wmm@fastdial.net
Software Emancipation Technology (www.setech.com)


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
---
[ 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              ]





Author: Paul Lennon <plennon@kofax.com>
Date: 1999/07/06
Raw View
Hi,

Thanks for all the comments.  Sorry about the "char[] text;" error.
Yes, I meant "char text[];"

I asked this question after we discovered a few instances of similar
code during a project code review.  Presently we don't think the
application is suffering, we just weren't sure if this was okay.  After
reading the comments it sounds like we should do our best to avoid this
situation completely.

Thank you all for your time,

Paul Lennon
Tyngsboro, MA
---
[ 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              ]





Author: comeau@panix.com (Greg Comeau)
Date: 1999/07/06
Raw View
In article <378016C9.C947149F@acm.org> Pete Becker <petebecker@acm.org> writes:
>James Kuyper wrote:
>>
>> In C9X, they are finally standardizing the traditional "struct hack",
>> whereby a short array at the end of a struct is indexed beyond it's
>> nominal lenght to access memory allocated beyond the nominal size of the
>> struct. 'char[] text;' is precisely the sytax that they are legalizing
>> for doing this. I'd recommend that as soon at C9X is approved, someone
>> should start thinking through the implications for adopting that
>> construct into C++.

I clearly see the temptation to allow this facility of
"flexible array members" to C9X but IMO it is a narrow-minded hack.
I certainly hope that the C++ committee does not adopt it.

>> Obviously, it's not as necessary in C++, where we
>> have vector<> or string or valarray<> to serve the same purpose in a
>> safer fashion.

For sure.  There are even alternatives, some would say superior, in C.

>However, should it at least be made legal, for
>> compatibility with C9X? Obviously, such a struct could only usefully be
>> created using placement new, or malloc() for POD structs.
>
>There's a major problem with allowing this in C++: it produces a type
>that cannot be derived from.

You don't even need to look that far.  As I recall the feature,
I don't even think you would always be able to assign it to something
else in C++ (I could have this wrong).

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***


[ 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              ]






Author: blargg@flash.net
Date: 1999/07/06
Raw View
In article <377F65AE.5DCAEE74@wizard.net>, James Kuyper
<kuyper@wizard.net> wrote:

[snip]

[ struct X {
    int size;
    char data [];
};]

> In C9X, they are finally standardizing the traditional "struct hack",
> whereby a short array at the end of a struct is indexed beyond it's
> nominal lenght to access memory allocated beyond the nominal size of the
> struct. 'char[] text;' is precisely the sytax that they are legalizing
> for doing this. I'd recommend that as soon at C9X is approved, someone
> should start thinking through the implications for adopting that
> construct into C++. Obviously, it's not as necessary in C++, where we
> have vector<> or string or valarray<> to serve the same purpose in a
> safer fashion.

Huh? I figure the purpose of this "hack" is to reduce the number of
freestore allocations by one, i.e. allocate the variable number of
elements along with the extra information. I suppose it also has the
effect of making it simpler to access it all directly in C too, which is
the point you're addressing.

> However, should it at least be made legal, for
> compatibility with C9X? Obviously, such a struct could only usefully be
> created using placement new, or malloc() for POD structs.

<sarcasm>
Maybe we could add a new syntax

    new X.data [99];

Wow, and it wouldn't break any current programs!
</sarcasm>


[ 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              ]






Author: "Ken Hagan" <K.Hagan@thermoteknix.co.uk>
Date: 1999/07/07
Raw View
I wouldn't call this a major problem. There are already ways of
creating classes that you can't derive from, and we seem to survive.

Also, presumably we can't create arrays of such types either, and
presumably C9X acknowledges this.

The construct is presumably useful in cracking file formats, where
vector<> and valarray<> don't help. MS already support the feature
(with the syntax "char text[];"), perhaps because Windows has a
number of such formats.

Pete Becker wrote in message <378016C9.C947149F@acm.org>...
>There's a major problem with allowing this in C++: it produces a type
>that cannot be derived from.
---
[ 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              ]





Author: comeau@panix.com (Greg Comeau)
Date: 1999/07/07
Raw View
In article <newscache$vwkeef$2ba$1@firewall.thermoteknix.co.uk> "Ken Hagan" <K.Hagan@thermoteknix.co.uk> writes:
>The construct is presumably useful in cracking file formats,

And with communications.

>where vector<> and valarray<> don't help.

Sure they help.

>MS already support the feature (with the syntax "char text[];"),
>perhaps because Windows has a number of such formats.

Some compilers have supported this for years (some on purpose,
others as bugs).  Actually, Comeau C++ supports it for compatibility
with MSVC++ (we need to support MS features and bugs), but otherwise
it is not recommended.  As Pete mentioned, you cannot use it as a base
class, nor can it have things like a virtual base class itself.

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***
---
[ 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              ]