Size of a dynamic allocation

This topic is 4684 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I was looking at the auto_ptr example that Scott Meyers had in "More Effective C++". It hit me that the implementation works great for a single memory allocation. But it fails when dynamically allocating arrays. The destructor simply calls delete, instead of the needed delete[] in the case of an array. I don't know of anyway to determine if the pointer that was passed to the function points to a dynamicly allocated array or just a single dynamically allocated variable. Is there anyway to determine if it is? The only arguement that I can make that it might be remotely possible is the fact that somewhere the size is stored so delete[] knows how much memory to release. But I also figure this is probably upto the compiler where this kind of info is stored, so there really isn't a universal way to do this. Any ideas?

Share on other sites
It's not possible to look at a pointer and know. In fact, I don't think there's even any non-portable way of doing it.

boost, for example, has scoped_ptr and scoped_array for that exact reason. ( Which you should be using instead of Meyer's version, BTW. )
http://boost.org/libs/smart_ptr/smart_ptr.htm

Share on other sites
I figured it would require to disinguish between the two. Like I said, I think what just kind of bugs me is that fact that somewhere in memory there must be a table that has how much memory was allocated, since it knows how much to delocate. But I'm sure that's one of those things that the standards committe said, we don't care how you do it, you just need to do it.

Share on other sites
Maybe you want to read the book "Modern C++ Design" from Andrei Alexandrescu:
http://www.moderncppdesign.com/book/main.html

There is a chapter about Smart Pointers:
http://www.informit.com/articles/article.asp?p=25264&redir=1

If you want to automatically call the correct delete function, your pointer has to keep track of that fact. So you may write a smart pointer with 'delete traits'.

Example, feel free to extend:
template <typename T, typename delete_traits>class MyPointer {T* pointer;...// somewhere a call like thisdelete_traits::delete_pointer(pointer);...};

template <typename T>struct delete_object {  static inline void delete_pointer(T* pointer) {    delete pointer;  }};template <typename T>struct delete_array {  static inline void delete_pointer(T* pointer) {    delete[] pointer;  }};

// for arraysMyPointer<int, delete_object<int> > mp(new int[100]);