|
> If memory management is a serious problem for the software you work on, I've never found the boost library lacking. As a developer that isn't working with C++, I'm finding memory management in C++ to be a nightmare and no amount of libraries can solve it. Say you receive a pointer from somewhere. Is the referenced value allocated on the stack or on the heap? If allocated on the heap, do you need to free it yourself, or is it managed by whatever factory passed it to you? If you need to deallocate that value, is it safe doing so? Maybe another thread is using it right now. If you received it, but it should get deallocated by the factory that gave it to you, then how will the factory know that your copy is no longer in use? Maybe it's automatic, maybe you need to call some method, the only way to know is to read the docs or source-code very carefully for every third-party piece of code you interact with. All of this is context that you have to keep in your head for everything you do. No matter how good you are, not matter how sane your practices are, it's easy to make accidental mistakes. I just reissued my SSL certificate, thanks to C++. Yeah, for your own code you can use RAII, smart pointers, whatever is in boost these days and have consistent rules and policies for how allocation/deallocation happens. Yay! Still a nightmare. Even if manageable, there's a general rule of thumb that if a C++ project doesn't have multiple conflicting ways of dealing with memory management and multiple String classes, then it's not mature enough. |
Here's your problem. In general I don't want to be receiving a single pointer from anyone. Lately, I've found it helpful to think of pointers in C++ as special iterators rather than a referential relic from C. In such a mindset passing pointers around without an accompanying end iterator, or iteration count, just makes no sense. Anywhere that implied iteration count is always a constant, I'm probably not structuring my code correctly.
So my recommendation is to use references (foo&) for passing down (well, up) the stack, never to heap allocated objects. Because you can't use delete on a reference there's no longer an ambiguity. Use smart pointers to manage the heap. Write RAII wrappers (it's not a lot of code) to manage external resources. RAII wrappers are especially useful for encapsulating smart pointers so big things can be passed around with value semantics, which gives you even stronger ability to reason. Implementing optimisations like copy-on-write becomes fairly trivial.
> I just reissued my SSL certificate, thanks to C++.
If you're referring to Heartbleed then OpenSSL is written in C, not C++. Generally only a language that inserts array bounds checks for every access would have shielded you from this bug... C++s <vector> does this if you use the at() function of <vector>, but op[] doesn't by default for performance reasons.