[Gc] Correct, portable array cleanup?
ntoronto at cs.byu.edu
Tue Apr 19 03:04:24 PDT 2005
Okay, so I'm new and spamming the list already, but I think I may be
onto something. From gc_cpp.h:
"Implementing clean-up of arrays correctly, portably, and in a way that
preserves the correct exception semantics requires a language extension,
e.g. the 'gc' keyword."
I've made a stab, and I don't know enough about exception semantics to
say this is correct, but I think it is. (What ARE correct exception
semantics during garbage collection?)
I've put the first draft online here:
array<A> a(10); // allocates an array of 10 elements, handle is 'a'
array<B> b(5, "Ha ha"); // allocates an array of 5 elements, handle 'b',
calls B::B(const char*) for each
for (int i = 0; i < a.size(); i++)
a[i] = ...
... = b[i];
Advantages over naked pointers:
- Objects in the array have destructors called when the array is GCd.
- Can't point at an array of descendants with a base pointer. For example:
class B : public A;
A* p = new B; // compiles fine - icky, bad and evil
array<A> p = array<B>(20); // illegal - can't convert from array<B> to
- Bounds-checked access and NULL-pointer check when NDEBUG isn't defined.
- Exception-safe allocation (can safely use "array<T_>(...)" as a
function parameter - see https://www.gotw.ca/gotw/056.htm -
"Exception-Safe Function Calls").
- Takes as much space as a naked pointer (sizeof(array<T_>) == sizeof(T_*)).
- Extra level of indirection - access is slower (working on this with a
placement-new solution - hopefully I can make it portable)
- Contained object constructors are limited to 20 arguments (can be
expanded to arbitrary numbers using recursion a la Boost)
Since I haven't played with the collector much, comments are very welcome.
More information about the Gc