How to check if dynamic memory is there before deleting?

Started by
18 comments, last by JTippetts 11 years, 3 months ago
Look into boost::shared_ptr and boost::weak_ptr.

Handling pointers to objects is inherently difficult because in many cases you'll want to pass off or store copies of those pointers. Then you need to deal with knowing when it's safe to delete. It's a problem of ownership. You either have strict ownership or you have a mechanism for knowing when it's safe to delete. If you're not that experienced then you can easily fall into traps you've set for yourself. Using shared_ptr and weak_ptr together can help you solve the problem of ownership and get rid of the need for deletes.

shared_ptr and weak_ptr are part of the C++ standard now, so no need to introduce a boost dependency.

@Shaquil: new allocates memory and calls the constructor, delete calls the destructor and deletes memory. Now you know what new/delete do, so you don't have to worry about it anymore and can just use shared/weak/unique ptrs. Also, don't worry about using a vector being "overkill." Overkilling what? It's a dynamically managed array. It's not like using a guided missile to hammer a nail or anything, it's just a slightly safer hammer. Use the standard library (not STL; the STL became the standard library quite a few years ago, and now it's just the standard library), become familiar with it, learn which containers are best for which situations. That's why it's there. It's standard. Not-Invented-Here syndrome is counterproductive and leads to buggy code in the hands of inexperienced programmers.

I'm in the midst of a redesign of my core framework for Goblinson Crusoe, and there is not a single new or delete in sight anywhere in the code. Not one. The standard is getting to the point where they simply aren't necessary for 90% of the code we write, and that other 10% probably isn't going to apply for most people. If you carefully analyze the use cases for each piece of memory you allocate, you can make a choice of the proper pointer type to use. This analysis can also help to expose flaws in your design, so that's a bonus.

This topic is closed to new replies.

Advertisement