Good question but I think your example is a bad one! Your LOOP
macro does not make anything clearer - it actually hides your intent from programmers who don't use your macro, and it doesn't even look like C++ - my first reaction to your snippet would be "is that even C++?" or "what's wrong with an ordinary for
?". It may be tedious to write the loops over and over, but we all know everyone spends a lot more time reading and maintaining code than writing it in the first place, so it's hardly a waste of time writing out a full for
, and it's much clearer. You can continue to argue your point, but you should be aware that using macros in that way is not a widely accepted technique - other people looking at your code will call you out on it too.
Anyway, to add an actual answer - my favourite idiom in C++0x is a vector of unique_ptr:
std::vector<std::unique_ptr<T>> my_container;
It has the following advantages - essentially a safe vector of pointers:
- It provides random access in O(1) time
- Elements are guaranteed to never move in memory even when reallocating (so you can safely take the address of
T
s and store them)
- Fast for tasks like sorting (just shuffling some pointers, not copying heavyweight objects)
- Exception safe and helps prevent memory leaks -
erase()
on an element also releases the memory
- Flexible - you can
std::move()
pointers out of the container and put them somewhere else
It does have one or two disadvantages:
- Each element is allocated on the heap which may have performance implications if adding/removing a lot of elements, plus elements can be far apart in memory losing cache locality
- Iteration requires double indirection
(*i)->member
syntax - but I don't think it's a big deal
However, especially for heavyweight objects, I think it is nearly an ideal container.