[gdal-dev] Simplifying malloc'action with simple templates

Mateusz Loskot mateusz at loskot.net
Sat Jan 9 16:12:34 EST 2010


Philippe Vachon wrote:
> Hi Mateusz,
> 
> I would actually wonder if a solution like this would work:
> 
> /// @brief Allocate memory on the heap and return a pointer of type T.
> /// @param ptr pointer to be populated to the allocated memory
> /// @param size the size of a single object to be allocated (or of the entire region)
> /// @param nmemb optional, the number of regions to be allocated. The resulting region would be size * nmemb.
> /// ...
> template <typename T>
> T *CPLMallocT(T*& ptr, std::size_t const size = sizeof(T), std::size_t const nmemb = 1) { ... }
> 
> This would enable replacing the VSIMalloc* routines (the ones that check for
> argument wraparound) with a single unified interface,
> and implicitly enable the last version of CPLMallocT that you
> proposed. So long as malloc() is still used under the hood,
> I presume {VSI,CPL}Free() will still behave as before.

Yes, it would work, or as this version:

template <typename T>
T* CPLMallocT(std::size_t const n = 1, std::size_t const size = sizeof(T))
{
   return static_cast<T*>(CPLMalloc(n * size));
}

Best regards,
-- 
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org


More information about the gdal-dev mailing list