tags:

views:

61

answers:

1

Especially for large scale projects where maintainability is important. Explanations, links/references are also welcome.

+1  A: 

C++ isn't normally in the business of saying xyz is best. this is because (in the C++ way of thinking) what works well in one C++ project, may not work well in another. this may even apply to the different parts of the same project.

what is really important is to adhere to basic good engineering practices:

  • whatever you decide, document the lifetimes of objects. it is difficult to figure out object lifetimes after-the-fact. this is the most important consideration for maintainability.

  • know your requirements. are you going to have to do cross-platform work? are you going to have to interface with other languages? all these will affect your memory management decisions. be careful of overengineering and underengineering.

  • kiss. automatic (stack) lifetime is often simpler than dynamic allocations. auto_ptr(or scoped_ptr) is usually simpler than shared_ptr. static globals are usually complex. pooling memory is usually complex. garbage collection (the boehms kind) can be simpler than smart_ptrs. BUT, all these rules have an asterix next to them, because quite frankly, the answer depends.

  • think really hard about possible hazards in multi-threading. i mention this because most people get it wrong. often, the most robust policy will be to not share ownership between threads.

  • understand how to use the common smart pointers so you can decide whether they're good for your project. don't write your own smart pointers, unless you really really need them. ambitious developers almost always get something wrong in writing their own smart pointers.

  • finally, if this is a new project, think really hard about if you actually have to use C++ for everything in your project or just a part. i love C++ just as much as the next guy, but realize that it can be like a gun without the safety on.

If this answer is overly general, its because the question is a very general one. If you provide more details, we can probably give a more detailed answer.

Lau Lau Labs
How should I implement aggregation in C++? E.g. an image class that has a vector of ints to store the image class and you also want to provide a cons that takes a vector of int and a better function for this. Should I copy the vector or use smart ptr or reference it?
ajay