On Jun 16, 12:10 pm, Ian Collins <ian-n...@hotmail.com> wrote:
> Paul Hsieh wrote:
> > On Jun 13, 8:15 pm, Keith Thompson <ks...@mib.org> wrote:
> >> Paul Hsieh <websn...@gmail.com> writes:
> >>> It also forces
> >>> you to be more exact in function declarations. This I found to be
> >>> the biggest actual source code impact, as it basically forces you
> >>> to cast all mallocs.
> >> Right (but it's usually better practice to use new and delete in C++
> >> anyway, or some STL type that manages memory for you).
>
> > C++ is built on the RAII principle.
>
> Is it?
All struct or class declarations invoke whatever the default
constructor it has. Furthermore any class with a constructor must
invoke a constructor at the time of declaration. That's basically
what RAII is -- a method of synchronizing allocation and
initialization.
> > Using new and delete invoke
> > constructors which you might not want to happen. Furthermore, its
> > easy to show that STL's vector templates have either ridiculously bad
> > performance in comparison to hand managed realloc()'s precisely
> > because of the RAII overhead or else compromise your design to the
> > point that you might as well use realloc().
>
> Care to demonstrate?
Sure. Lets make a class of mail messages. Note that its impossible
to have an empty mail message (because there is always at least a
header), hence a mail message can only be initialized based on some
input text stream or string; there is no well defined concept of a
default mail message constructor. Further it makes very little sense
to mutate a mail message by changing its contents after the fact. So
its a well motivated read-only class without an empty or default
constructor.
Now lets say you want to have a dynamic vector of mail messages (this
is exactly what you would expect a deserialized mailbox essentially to
be). The implementation of STL vectors require that the class have a
default constructor if the vector is modified (which it would be as a
result of incrementally reading the mailbox).
There are numerous work arounds to this such as creating a wrapper
class which does have an empty constructor which hides a pointer to a
mail message class that starts out NULL. But individual new()s to
each one is still going to take extra overhead (performance + memory)
so you would prefer to point into a memory pool of your own which you
maintain with malloc() or realloc() anyways, in which case you have
not saved or improved anything by using these C++ constructs.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/