Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

People who are used to garbage collected languages are often scared of C++'s memory management. There are tools, like auto_ptr and shared_ptr which will handle many of the memory management tasks for you. Lots of C++ libraries predate those tools, and have their own way to handle the memory management tasks.

How much time do you spend on memory management tasks?

I suspect that it is highly dependent on the set of libraries you use, so please say which ones your answer applies to, and if they make it better or worse.

share|improve this question
1  
Not that much, really... Especially with C++0x, references and STL. You can even write code with no memory management at all. –  Coder Oct 3 '11 at 13:56
8  
In general: Not that much if you are experienced. A lot if you are novice to C++ (-> usually hunting memory/resource leaks). –  MaR Oct 3 '11 at 14:34
1  
I find the real question, these days, more being about chasing down stale references. And it's usually pretty evident each time, just annoying that it was not caught before :p –  Matthieu M. Oct 3 '11 at 18:04
    
I know this is old, but IMO memory management is an integral part of being a good programmer. Abstractions like the STL containers are nice, but ignorance of memory is against the very idea of computation itself. One might as well ask how one can eliminate algebraic manipulation, logic, and looping from the programmer's arsenal. –  imallett Apr 30 at 4:22

7 Answers 7

Depends on the senior technical leads in the team. In some companies ( including mine ), there is no concept called smart poiner. It is considered fancy. So, people simply put deletes all over the place and there is a drive for memory leak fixing for every 2 months. New wave of delete statements arrive everywhere. So, depends on the company and the kind of people who work there.

share|improve this answer
1  
Is there something in your environment that stops you from using auto_ptr and friends? –  Sean McMillan Oct 7 '11 at 12:30
1  
sounds like your company doesn't write C++ code, you're writing C. –  gbjbaanb Dec 23 '13 at 23:08

When I was a C++ programmer (a long time ago), I spent a long time worry about memory management bug when trying to fix hard to reproduce bugs.

With modem C++, memory management is a lot less of an issue, but can you trust everyone on a large team to get it right. What is the cost/time of:

  • Training (not many programers arive with a good understanding of the issues)
  • Code reviews to find memory management issues
  • Debugging of memory management issues
  • Always having to keep in mind that a bug in one part of the app, may be due to a memory management issue in a unrelated part of the app.

So it is not just the time spending “doing”, this is more of an issue on large projects.

share|improve this answer
1  
I think some C++ projects have despaired of ever fixing some of their memory leaks due to badly written code. Bad code is going to happen, and when it does it can take up a lot of other people's time as well. –  Jeremy Oct 3 '11 at 19:29
    
@Jeremy, I found when I moved from C++ to C#, there was still as much badly written code (if not more), but at least it was a lot easy to find the part of the program that had a given bug. –  Ian Oct 3 '11 at 20:12
1  
yes this is a lot of why most shops have moved to Java or .NET. Garbage collection mitigates the inevitable damage of bad code. –  Jeremy Oct 3 '11 at 20:35
1  
Oddly enough, we don't have those problems. –  David Thornley Oct 3 '11 at 20:52
1  
@DavidThornley, I think a lot of the problem were from writing UI code in C++, these days most C++ code I see is not UI –  Ian Oct 4 '11 at 8:33

how much time does it take as a client? very little, once you get the hang of it. when a container manages lifetime and references, it's really very easy. imo, it's far simpler than manual reference counting, and it's practically transparent if you consider the container you use as documentation which the compiler conveniently prevents you from performing invalid ownership transfers in a well designed typesafe system.

most of the time i spend (as a client) is spent containing types from other apis, so they function well within the context of your programs. example: this is my ThirdPartyFont container, and it supports these features, and implements destruction this way, and reference counting this way, and copying this way, and.... Many of those constructs need to be in place, and it's often the logical place to put them. whether you want to include that as time or not depends on your definition (the implementation needs to exist when interfacing with these apis, anyway, right?).

after that, you will need to take memory and ownership into consideration. in a lower level system, that's good and necessary, but it can take some time and scaffolding to implement how you should move things around. i don't see it as a pain since this is a requirement of a lower level system. ownership, control, and responsibility are evident.

so we can turn that towards c based apis which use opaque types: our containers allow us to abstract all the little implementation details of managing the lifetime and copying of those opaque types, which ultimately makes resource management very very simple and saves time, defects, and reduces implementations.

it's really very simple to use these - the problem (coming from GC) is that you have to now consider your resources' lifetimes. if you get it wrong, it can take a lot of time to solve. learning and integrating explicit lifetime management is understandably complex in comparison (not for all people) -- that's the real hurdle. once you are comfortable controlling lifetimes and using good solutions, then it's really very easy to manage resource lifetimes. it's not a significant part of my day (unless a difficult bug has crept in).

if you're not using containers (auto/shared pointer), then you're just pleading for pain.

i've implemented my own libraries. it takes me time to implement those things, but most people reuse (which is usually a good idea).

share|improve this answer

Memory management is used to scare children, but it is only one kind of resource that a programmer has to look after. Think file handles, network connections, other resources that you obtain from the OS.

The languages that support garbage collection usually not only ignore the existence of these resources, but they also make it harder to handle these properly by not providing a destructor.

So, in short, I'd suggest not that much of a C++ developer's time is spent worrying about memory management. As klaim's answer indicates, once you get a handle on RAII, the rest is just reflex.

share|improve this answer
3  
I especially love how HttpWebRequest.GetResponse leaks handles and starts crashing in GC languages. GC is cool, until it starts sucking because resources still leak. msdn.microsoft.com/en-us/library/… See "Caution". –  Coder Oct 3 '11 at 14:50
5  
+1 for viewing memory as resource. Legacy code or not, how many times do we need to shout out loud: Memory management is a skill and not a curse. –  aquaherd Oct 3 '11 at 16:16
4  
@Coder Not sure if I follow.. GC sucks because it's possible to abuse resources anyway..? I think C# does a good job providing deterministic resource releasing using IDisposable... –  Max Oct 3 '11 at 16:32
8  
@Max: Because if it's garbage collected, then I expect not to worry about stupid resources via using and custom IDisposables. Resources left the scope, that's it, they should be cleaned. In reality, though, I still have to think and guess which ones will leak, and which ones won't. Beats any reason to use GC language in the first place. –  Coder Oct 3 '11 at 16:52
4  
@deadalnix They do have the finalize construct. However, you don't know when it will be called. Will it be before you run out of sockets, or WebResponse objects? You'll find articles aplenty that tell you that you should not rely on finalize - with good reason. –  Dysaster Oct 3 '11 at 19:39

Modern C++ makes you not worry about memory management until you have to, that is until you need to organize your memory by hand, mostly for optimization purpose, or if the context forces you to do it (think big-constraints hardware). I've written whole games without manipulating raw memory, only worriing about using containers that are the right tool for the job, like in any language.

So it depends on the project but most of the time it's not memory management that you have to handle but only object life-time. That is solved using smart pointers, that is one of idiomatic C++ tool resulting from RAII.

Once you understand RAII, memory management will not be a problem.

Then when you'll need to access raw memory, you'll do it in very specific, localized and identifiable code, like in pool object implementations, not "everywhere".

Outside of this kind of code, you'll not need to manipulate memory, only objects lifetime.

The "hard" part is to understand RAII.

share|improve this answer
9  
Absolutely true. In the last 5 years, I've only written "delete"s when working with legacy code. –  drxzcl Oct 3 '11 at 15:36
3  
I work in a highly stack-size constrained embedded environment. As cool as RAII is, it does not work well if stack space is at a premium. So it's back to pointer micromanagement. –  bastibe Oct 3 '11 at 17:00
1  
@nikie I use the libraries smart pointers in the code that manipulate their API, then I use standard or boost smart pointers in code specific to my application (if I'm the one who decide about that). If you can isolate library code in some modules that abstract how they are used in your application, then you avoid API pollution from dependencies. –  Klaim Oct 3 '11 at 18:27
11  
@Paperflyer: RAII won't take up more stack space than delete manually, unless you have one shitty implementation. –  DeadMG Oct 3 '11 at 19:51
1  
RAII and shared_ptr/auto_ptr smart pointers are useful if your programmers are still newbies. Experienced people can use slightly better solution which gives better compile-time checking of the problems. –  tp1 Oct 4 '11 at 1:04

Pretty much none. Even old technologies like COM, you can write custom deleters for the Standard pointers that will convert them in a very short time. For example, std::unique_ptr can be converted to uniquely hold a COM reference with five lines of a custom deleter. Even if you have to manually write your own resource handler, the prevalence of knowledge like SRP and copy-and-swap makes it relatively easy to write a resource managing class to use forever more.

The reality is that shared, unique, and non ownership all ship with your C++11 compiler, and you just have to write small adapters to make them work even with old code.

share|improve this answer
    
How much skill with C++ do you have to have to a) write a custom deleteter b) know that a custom deleter is what you need? I ask because it seems easy to pick up a new GC'd language and get close-to-correct without know the whole thing -- it it easy to get right in C++ as well? –  Sean McMillan Oct 3 '11 at 19:46
1  
@SeanMcMillan: Custom deleters are trivial to write and deploy, the COM one I mentioned is five lines for all COM types, and anyone with a basic training in modern C++ should be familiar with them. You can't pick up a GCed language, because surprise- the GC won't collect COM objects. Or file handles. Or memory obtained from other systems. Or database connections. RAII will do all of those things. –  DeadMG Oct 4 '11 at 8:31
1  
By "Pick up a GC'd language," I meant that I've hopped between Java/C#/Ruby/Perl/Javascript/Python, and they all have the same resource management style -- memory is mostly automatic, and everything else, you have to manage. It sounds to me like you're saying C++'s management tools let you manage file handles/db connections/etc in the same way as memory, and that it's relatively straightforward once you learn it. Not brain surgery. Do I understand correctly? –  Sean McMillan Oct 4 '11 at 12:58
2  
@SeanMcMillan: Yes, that's exactly right, and it's not complex. –  DeadMG Oct 4 '11 at 19:21

I use boost and TR1 libraries a lot, and they make memory management in the strict sense (new/delete) a non-issue. On the other hand, memory allocation in C++ is not cheap, and one must pay attention to where these fancy shared pointers are created. You end up using workspaces a lot, or working with stack-based memory. In general, I'd say that it's mostly a design problem, not an implementation problem.

share|improve this answer

protected by GlenH7 Dec 24 '13 at 14:13

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.