Most of my C++ programming experience has been projects for school. In that way, our usage of external libraries (ie boost) has been either prohibited or discouraged. Therefore we could not use smart pointers unless we wanted to write our own, which was usually beyon开发者_运维百科d the scope of the projects. I'm just wondering in real world projects, how much memory management is actually done manually?
I guess this is sort of a vague question. I'm just wondering how memory management is usually done in real world projects.
On legacy code there's usually a lot of manual memory management. If someone hadn't take the time to refactor it you can find a lot of naked news and deletes, just happily waiting to leak somewhere.
I believe most recent, well written, software in C++ usually do use smart pointers, RAII, and so on. Manual memory management is error prone.
In the few projects I wasn't allowed boost, on one of them, I did roll a rudimentary smart pointer.
That said, in the real world, use boost. Use third party libraries. If a wheel is out there, don't reinvent it. You'll be more productive, and you'll spend less time tediously writing code someone else has already written.
Depends what you mean by "memory management".
Obviously, a strict definition means "all the time", since automatic variables (stack allocated) is a memory thing. You probably didn't intend that.
On the other side, there is raw new
and delete
usage. This should never happen, but probably happens in "common" C++ anyway. It's bad practice, sloppy, and easily solvable with containers. One can literally copy and paste a smart pointer implementation from somewhere and be done, no excuse.
In the middle, ideally all "management" is done automatically, with containers. The only management that might need to be done is breaking cyclic dependencies or making your own container classes.
In my own projects, I only ever use new
and delete
when I'm making a utility class so I never have to new
and delete
again. After that, I only use new
when it goes directly into some container.
In the real world there is both. You'll most likely see more project code out there that desn't make use of smart pointers. The use of new and delete is most prevalent.
That being said, more and more programmers are using boost and smart pointers in their projects now and I've seen some code refactored to use boost::shared_ptr as well
It is also worth mentioning that shared_ptr made it into the standard library in 2003 as std::tr1::shared_ptr. Or at least, if it isn't officially in the library, it is shipping with all the C++ compilers I've used recently.
精彩评论