I usually prefer the smallest amount possible, so I create the object as late as possible and I release them as soon as possible.
I will tend to have:
char * foo; { foo = create(); destroy(foo); } { foo = create(); destroy(foo); }
Even if I could reuse the memory, I prefer to allocate it twice and release it twice. In most cases, the performance of this method is very small, since in most cases the two objects are different in any case, and if this is a problem, I try to optimize this recently in the dev process.
Now, if you have 2 objects with the same scope (or three as an example), this is the same:
{ foo1 = create(); foo2 = create(); foo3 = create(); /* do something */ destroy(foo1); destroy(foo4); destroy(foo3); }
But this particular layout is applicable only when three objects have the same scope.
I try to avoid such a layout:
{ foo1 = create(); { foo2 = create(); } destroy(foo1); destroy(foo2); }
I think it's broken.
Of course, {} is given here just for an example, but you can also use them in actual code, or vim folds or anything that denotes a region.
When I need a wider scope (for example, global or general), I use a reference counter and a save mechanism (replace create with save and delete with release), and this always provides me with a nice and easy memory management.
Nicolas goy
source share