Sign in to follow this  
zyrolasting

[C++] new[]/delete[] usage

Recommended Posts

I use a managed heap that understands the use of new/delete and new[]/delete[]. I'd like to slim this down, if I can. If I were to allocate all single instances with new val[1] so I can always use delete[] even with single instances, would I be wasting much?

Share this post


Link to post
Share on other sites
I don't get it. You want to make more typing for yourself by using new[] and delete[] for times that new and delete are clearly sufficient?
You'd be wasting some number of keystrokes, bytes, and processor cycles for a start.
If you ever have a variable that you need to delete or delete[] and you don't immediately know which one then you're doing something wrong!

Share this post


Link to post
Share on other sites
If you are thinking about doing something like this you are using new and delete wrong. You should only use new and delete when it is necessary. This would mean you have no idea how much memory is going to be needed to store the object. That is why they are used to allocate memory dynamically. For instance you have a Image object that you are going to store a image in. You can't guarantee how much memory that image is going to take up. So you can new it. Then use it by only obtaining a reference to prevent you from having duplicates. Then when you are done using it you can delete to free up the memory it was occupying.

If you want a managed heap use something like C# where all objects always go on the heap and the runtime's heap is optimized for such use. When it comes to C++ it is common practice to avoid putting objects on the heap with new, unless you absolutely have no choice but to do so. In C++ every time you use new is another chance to cause a memory leak in complicated code.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this