1. Should Free Pascal care about the destruction of an object instance (use a destructor), if the variable that referred to this instance began to refer to another? For example:

    a:vector; a := vector.create(x1,y1); {вот "а" стало ссылаться на один объект класса vector} a := vector.create(x2,y2); {а теперь "а" стало ссылаться на другой объект класса vector} 

    Will the first class object be removed from memory? If not, how to make it so?

  2. Where can I read in detail about OOP in Delphi / FreePascal? It is about the OOP tools in these environments.

  3. Correctly, I understand that if I overloaded the operator:

     operator *(a:vector;b:single)c:vector; begin c:=vector.create(ax*b,ay*b); end; 

    and then, for example, used this statement like this:

     a1:=a1*b1 {a1,b1 и c1 типа vector } 

    something is wrong, you need to use it like this:

     с1 := a1; a1 := c1 * b1; c1.free; 

2 answers 2

In your case, the first object will not go anywhere, but it will no longer be available for use. The variable a is, in essence, a pointer to the section of memory where the object created by the Create constructor is located. That is, at the beginning you create the first object and its address is entered into the variable, and then the second, and its address overwrites the address of the first.

@Yura Ivanov , wrote how to properly destroy waste objects. From myself I want to add that if exceptions can work in the code for working with an object, then it needs to be escaped with a try/finally/end construct. This will enable the guaranteed destruction of the object.

 a := vector.create(x1,y1); try // Здесь работаем с объектом "a" finally a.Free; end; 

Also, for the destruction of objects there is a procedure FreeAndNil() . In addition to the destruction of the object, it also resets the variable. This is convenient if the code has checks through Assigned() an object is created or not.

  • From myself I want to add that try / finally / end is better to use even in cases where no exceptions are expected. - AlexAndR

TObject is the base class for all classes. If your vector inherited from it or its descendants (if it is declared as a class, it will already be a descendant of TObject ), then it has Destroy destructor, which is usually called not directly, but via the Free method. Those.

 MyObj := TMyObject.Create; {какие-либо действия над объектом} MyObj.Free; MyObj := TMyObject.Create; {работаем с другим объектом} MyObj.Free; 

But it is better to use different variables for the readability of the code.