Re: Methods returning const char*'s [or similar] - am I responsible for freeing the pointer or not?
Re: Methods returning const char*'s [or similar] - am I responsible for freeing the pointer or not?
- Subject: Re: Methods returning const char*'s [or similar] - am I responsible for freeing the pointer or not?
- From: Allan Odgaard <email@hidden>
- Date: Thu, 4 Mar 2004 11:46:21 +0100
On 4. Mar 2004, at 10:20, Wade Tregaskis wrote:
Basically I'm wondering whether I should be freeing const pointers
returned by various system/library methods.
It depends on the system/library.
ANSI-C has some stuff which you must free(), like malloc and strdup.
C++ generally returns by-value. There should be nothing in the standard
library which return something you must explicitly delete. You only
delete what you allocate yourself (by the use of new, not member data
or objects with automatic storage).
In particular, I'm thinking that it'd be a pretty silly thing to
return an internal storage buffer - whether const or not - in a
situation where that buffer may be deallocated before external
references to it are removed (e.g. in the case where the buffer refers
to some property of an object like a UI element).
There are no such cases in the standard library which I am aware of.
C++ generally use deep-copy and return by-value.
But my memory tells me that a const pointer implies you shouldn't free
it, since it's "const" and not my responsibility to manage.
There are two types of const here. Mutable pointer to constant data,
e.g. "char const*", and constant pointer to mutable data, e.g. "char*
const". But you can delete both.
But for the reason I've already stated that seems like a foolish and
impossible demand to place on the developer, to try and synchronise
external references to buffers with their life spans. It also seems
to directly break many [most?] fundamental black-box design
principles.
I don't know from where you have this convention, but I have not heard
about it. If you look at Apple's non-OO APIs you'll see that each
CreateXYZ-function is matched by a DisposeXYZ-function.
This is the convention in ANSI-C I guess... in C++ one generally tries
to do memory management more "automatic". For example if you need to
return an object/buffer that the user needs to deallocate, you wrap it
in std::auto_ptr (for automatic disposal when the pointer goes out of
scope, unless ownership hans been transferred).
But generally you return by-value, to achieve the same effect (to
overcome the overhead of a deep-copy one either uses the
pointer-to-implementation idiom, or uses const references for result
variables (or argument variables for that matter)).
In modern C++ you rarely see explicit new and delete statements.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.