Auto pointers and arrays

Started by
4 comments, last by Emmanuel Deloget 17 years, 12 months ago
I'm currently using std::auto_ptr in a function where a lot of memory is allocated at the beginning, and multiple returns paths exist. So the only real reason I'm using it is so that I don't have to explicitly delete the memory myself at every return path. The problem is that one of my allocations is for an array, and std::auto_ptr is strictly non-array. From what I understand, the different between delete and delete [] is that the latter calls the destructor on each object, whereas if you were to use delete on an array the destructor would only be called on the first element. However, what I'm dealing with is simply an array of floats. The next best thing I could do is graduate to a boost::shared_ptr or boost::scoped_array, but I really don't think I *need* them in this case. The bottom line is, would I be able to get away with using an std::auto_ptr on an array of floats and not have anything blow up in my face? Or would the code design fairy come hurt me in my sleep?
Advertisement
std::vector should be quite adequate. Just size it at construction, and use operator[] instead of push_back. There won't be any performance overhead.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
That's probably the way to go instead of worrying about the dynamic allocation. I guess sometimes I lose sight of the forest in favor of the trees :)
Quote:Original post by Zipster
The bottom line is, would I be able to get away with using an std::auto_ptr on an array of floats and not have anything blow up in my face?


nope.
This space for rent.
Then to satiate my own curiosity, could you elaborate on why it wouldn't work? If my understanding of the difference between "delete" and "delete []" is correct, then surely there wouldn't be a problem for scalar types since the memory is free'd either way. Unless I'm missing something. I've looked through the standard and it doesn't go into much detail unfortunately.
Quote:Original post by Zipster
Then to satiate my own curiosity, could you elaborate on why it wouldn't work? If my understanding of the difference between "delete" and "delete []" is correct, then surely there wouldn't be a problem for scalar types since the memory is free'd either way. Unless I'm missing something. I've looked through the standard and it doesn't go into much detail unfortunately.


There is no guarantee that delete and delete [] work in the same way for POD types. The standard does not go very deep because it is an implementation defined behavior.

Regards,

This topic is closed to new replies.

Advertisement