Re: Dynamically allocated classes
kanze wrote:
Ulrich Eckhardt wrote:
Theo Richter wrote:
item* pencil = new item;
Two things here:
- Don't use new unless you have to, this is not Java.
This depends on the type of the object. My impression is that
Items are entity objects, not simply values. If that is the
case, they will normally be dyamically allocated.
True. You cannot pass entities 'by value' (i.e. using copying) so
the 'unless you have to' doesn't apply. Other than that, the fact that
something resembles a real-world object doesn't mean that the
representation inside a program must be an entity, in particular for an
item in a stockroom it will often be just a recordset with some predefined
fields like article-number, vendor-ID and a description (i.e. what you
would put into a database).
- Don't use raw pointers but some smart pointer type.
That's pretty strange advice. About 80% of my pointers are raw
pointers. I only use smart pointers when I need some special
semantics, which isn't usually the case.
If you're not using garbage collection, then you'll probably
need smart pointers more frequently, but still not
systematically. In practice, for example, entity objects
(which, as mentionned above, should be most of your dynamically
allocated objects) should rarely be managed by smart pointers.
Hmmm. I guess using GC shifts the code towards using raw pointers.
Otherwise, I see two cases of pointers:
1. pointers to dynamically allocated storage
2. pointers that are passed to legacy APIs or that reference an optional
object (like the parameter to time()).
For the second category, smart pointers make no sense, but for the former I
use smart pointers almost exclusively. The only regular exceptions I
regularly make is when implementing PIMPLs (because auto_ptr can't be used,
shared_ptr has unnecessary overhead and there is no sharing going on and
it's just too simple to do get it wrong) and sometimes for the handful of
permanent, global objects that make up my programs (I sometimes don't even
bother deleting them).
How do you get such a high percentage of raw pointers? Also, I guess that
exception safety is not one of the 'special semantics' you use smart
pointers for but a normal semantic that all your code has, right?
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]