On 6/15/06, Al Boldi <[EMAIL PROTECTED]> wrote:
Bram Kuijvenhoven wrote:
> Al Boldi wrote:
> > Bram Kuijvenhoven wrote:
> >> function TAncestor.ToStringSafe:string;
> >> begin
> >> if self=nil then Exit('<nil>');
> >> Result:=ToString; // now it's safe to call the virtual method
> >> end;
> >
> > Are you sure it's really safe to call?
>
> I think so: function ToStringSafe:string; is not virtual. You can check it
> yourself by running the code.
Did you ever try calling an instantiated TObject.Free twice?
An invalid self is conceptually incorrect. Think about it.
It would mean, that you are running inside code that doesn't really exist.
Does this have any meaning other than being some strange hack?
It's conceptually wrong from the language POV, but unfortunately not
from the machine's POV.
As I said before, 'Self' is just a parameter passed to the function.
If you call 'someobj.Free' you are calling the function 'Free' passing
'someobj' as the 'Self parameter'.
So, from the machine's POV the code always exist, but the object data
(pointed by Self) may be invalid.
You must allow several variables to point to the same "object",
otherwise the language would be useless (guess I'll try that some day
;-), so you need to have a central access point. One can _try_ to
detect invalid object accesses by adding a 'magic number' to objects
(to mark them either valid or invalid), but the only really safe way
is to use a garbage collector (which aren't hugely appreciated and
would imply some limitations on 'pointers' usage).
> > BTW, is there a way to make Assigned(obj) really check for a valid
> > pointer?
>
> Not really.
> - When destroying an object, the pointer is invalid, but still points to a
> memory area with about the same data as before; how would you see the
> difference
It should at least reset the calling pointer to nil.
Since 'Free' is a standard method it can't do that. For now the best
one can do is to always use 'FreeAndNil' function.
And of course this won't help a single bit if the object is being
pointed by other variables/objects, which IMHO is a much more common
error...
Cheers,
Flávio
_________________________________________________________________
To unsubscribe: mail [EMAIL PROTECTED] with
"unsubscribe" as the Subject
archives at http://www.lazarus.freepascal.org/mailarchives