Re: A few questions on C++
"D. Susman" <derya.susman@gmail.com> wrote in
news:1190206016.247651.88750@50g2000hsm.googlegroups.com:
Hi,
1) Should one prefer short / long to int in favour of better
compability? Does the sizeof(int) still vary dramatically between
platforms?
In many ways, the C++ type system is a mess for portability. Most of
the types are specified as minimum sizes, but they can all be bigger
than that. The good news is that universal portability isn't usually a
goal. That is, you usually don't have to write code that will work on
everything from embedded processors through mainframes. So, sometimes
you can make assumptions about the sizes involved in shorts and longs.
int is the native type for the machine and is at least as big as a
short. So, you can portably use it as a fast short.
2)Should one check a pointer for NULL before deleting it? Although
deleting a NULL pointer is said to be safe in C++, I see a lot of code
doing the check before deletion. Is this because they still preserve
the C attitude?
You do not have to check to see if the pointer is NULL before deleting.
This is indeed a holdover from old C days.
3) When is a struct favourable over a class?
The C++ STL seems to use structs for classes with no private members.
Personally, I only use structs for data only structures used with C
apis.
4) Should one favor '++iterator' over 'iterator++'? I did some
performance tests myself and did not see a big gap between their
execution times ( by using containers with size 10000000 which contain
objects )
The rule of thumb is to prefer ++iterator. You mostly see a difference
only when the class implementing ++ is a user defined class. The
reasoning is that there is a certain expense in maintaining the old
value to be returned after incrementing. With types like raw pointers
and scalars, you would be hard pressed to measure a difference, but if
an advantage is available under some conditions, you might as well take
advantage of it idiomatically by always using ++iterator. However,
having said that, it is even more important to follow whatever
conventions the code you are working with is following. No need to have
your code being the only chunks the use ++iterator just to possibly save
a clock cycle.
joe