Tuesday, 28 June 2011

New and delete

Sorry I haven't posted for a whole three! days. I just didn't think to record my thoughts.

Am I the only one who thinks these should be cut- yes, cut- from the language?

Firstly, thanks to variadic templates and perfect forwarding, they can be library functions, not language features (except placement new). And secondly, obscuring them behind some Standard types would make the specification much easier, and bugs much easier to avoid.

How would this be done?

Well, we'll invent a type, and we'll call it std::dynamic_array. It will likely be polymorphic. We will give it a size() method for the size of the array and an operator[] for accessing the elements. Then we will simply form unique_ptr and shared_ptr to it as necessary. We will have make_shared, make_unique, make_shared_array, make_unique_array, in my initial design, although I was also thinking of a kind of make_object

Why would we do this?

Firstly, new and delete as they are are buggy. I don't just mean the possibility of deleteing a pointer you got back from new[], or delete[]ing a pointer that's actually in the middle of an array you new[]ed, but also not knowing the size of the array. Altering the language in this way would prevent such misuse and clean up the specification. In addition, we can improve it to allow multi-dimensional variable length allocations as Standard, instead of having to hack it as we do currently.

As a language feature, our dynamic allocation should be the best it can be. The existing new and delete violate many design principles, RAII being the most prominent example, and the array-to-pointer conversion used in new[] is despicable. As such, they should be scrapped

No comments:

Post a Comment