The consequences of appropriating oneself

Found a piece of code today that I find a little smelly ...

TMyObject.LoadFromFile(const filename: String);
begin
  if fileExists(filename) then
    self := TSomeObjectStreamer.ReadObjectFromFile(filename);
end;

If this code works, it will at least skip some memory, but does it work? Is it possible to assign yourself in this way?

What if the stream object has a different subclass and then the original?
What if the stream object is different from another class that does not have a common ancestor to the original self?

+3
source share
3 answers

Self, , . , , -, .

+6

, , Self:

TMyClass.MyRoutine({args})  <=>  MyRoutine(Self: TMyClass {; args})

, "", .

, .

...

+2

yes, you can use self as a local temporary variable, even if it is useless here. But in this case, the stream object must be the same class as self (TMyObject), or the compiler will detect an error because the type is not compatible .

In your example TSomeObjectStreamer.ReadObjectFromFile(), TMyObject should return, or your compielr should warn you (or throw an error)

+1
source

Source: https://habr.com/ru/post/1739987/


All Articles