
vicente.botet wrote:
Hi,
On TBoost.STM, I need to do something before deleting an array on each one of the elements of the array, or more precissely with the address of each one of the elements.
T* ptr = new T[3];
// in another file, the number of elements to which ptr points is unknown. // before deleting for (size_t i=0; i< 'ptr size'; ++i) { // do something with &ptr[i] } delete [] ptr;
As the number of elemenst is unknow in the separated unit, I have no mean to iterate on ptr to get the address of the elements.
The C++ compiler or the C++ standard library knows this number of elements as it needs to call the destructor of each element when deleting the pointer. Is there something in Boost or a portable way to recover the number of elements of the array, maybe overloading the new [] operator and prefixing the allocate storage with some information? But what information can be stored so the implementation is portable?
There is no portable way to acquire the dynamic array length. IMO, there are two practical solutions for this: 1. Put everything you need into T's destructor. If T is a third party type then a wrapper class around T can serve the purpose. 2. Use a range wrapper instead of a raw pointer to the array. Regarding the trick with the prepended length storing, it can solve the problem, but it introduces pointer magic which may not be obvious for the ones reading the code (including yourself a couple months later). And, AFAIK, you won't be able to override the standard new and delete operators to behave that way, so you'll have to use dedicated functions to allocate/deallocate such arrays. Therefore I wouldn't recommend it unless there are significant reasons for it.