Delphi object reference model - delphi

I am trying to understand precisely how Delphi manages the memory and I have read from Marco Cantu that it uses references like Java does.
I have understood that a variable (let's say var theObj: TSomeClass;) holds a reference (= a pointer) to indicate the memory location where the object has been stored. So when I call the constructor of theObj I am creating the class on the heap and then theObj is a pointer to the newly created location.
So far so good but now I have the doubt. He says that:
In some OOP languages, declaring a variable of a class type creates an
instance of that class.
Does this mean that a pointer to a memory location is not involved? My guess is that here you declare a variable and it directly creates the object without using the heap. So is the variable only create on the stack and it holds all the data of the class?
Note. The guess and the question above are made because I made a comparison with C++.
Delphi: theObj := TSomeClass.Create
C++: TSomeClass *theObj = new TSomeClass;
Not going off topic and talking of C++ (it was just as example, I know only this language to make the comparison) but here in both cases I create the object in the heap and I have a pointer to it. The second question I made above came out because of this: in C++ I can also create an object like this TSomeClass theObj; and it will live until the end of the scope of the function.
In Delphi I cannot. I think that marco refers so this when he says "declaring a variable of a class type creates an instance of that class". Am I correct?

Marco is thinking of C++ where classes and structs are essentially the same with different default accessibility. In C++
SomeClass obj;
creates the object.
There is nothing for you to worry about. Your understanding, as expressed in the second paragraph, is impeccable. A Delphi variable of class type is, under the hood, just a pointer to the instance.

Related

Delphi Polymorphism using a "sibling" class type

We have an app that makes fairly extensive use of TIniFile. In the past we created our own descendant class, let's call it TMyIniFile, that overrides WriteString. We create one instance of this that the entire app uses. That instance is passed all around through properties and parameters, but the type of all of these is still TIniFile, since that is what it was originally. This seems to work, calling our overridden method through polymorphism, even though all the variable types are still TIniFile. This seems to be proper since we descend from TIniFile.
Now we are making some changes where we want to switch TMyIniFile to descend from TMemIniFile instead of TIniFile. Those are both descendants of TCustomIniFile. We'll also probably be overriding some more methods. I'm inclined to leave all the declarations as TIniFile even though technically our class is no longer a descendant of it, just to avoid having to change a lot of source files if I don't need to.
In every tutorial example of polymorphism, the variable is declared as the base class, and an instance is created of the descendant class and assigned to the variable of the base class. So I assume this is the "right" way to do it. What I'm looking at doing now will end up having the variables declared as, what I guess you'd call a "sibling" class, so this "seems wrong". Is this a bad thing to do? Am I asking for trouble, or does polymorphism actually allow for this sort of thing?
TIniFile and TMemIniFile are distinct classes that do not derive from each other, so you simply cannot create a TMemIniFile object and assign it to a TIniFile variable, and vice versa. The compiler won't let you do that. And using a type-cast to force it will be dangerous.
You will just have to update the rest of your code to change all of the TIniFile declarations to TCustomIniFile instead, which is the common ancestor for both classes. That is the "correct" thing to do.
The compiler is your friend - why would you lie to it by using the wrong type ... and if you do lie to it why would you expect it to know what you want it to do?
You should use a base class that you derive from, like TCustomIniFile. I would expect compile issues if you are trying to make assignments which are known at compile time to be wrong.
The different classes have different signatures so the compiler needs to know which class it is using to call the correct method or access the correct property. With virtual methods the different classes setup their own implementation of those methods so that the correct one is called - so using a pointer to a base type when you call the virtual method it calls that method in the derived type because it is in the class vtable.
So if the code does compile, it's very likely that the compiler will not be doing the right thing ...

Memory management of Objective-c object in c++ class

I am writing some iOS application and facing the decision whether to include objective-c object in a c++ class. After hours of search on the internet I found discussions of using (sometimes people use 'wrapping' instead of 'using') c++ class in objective-c are abundant while the opposite is quite limited. So my first question is, is it considered appropriate (and sometimes even necessary/convenient) to have objective-c data member in c++ class?
If this is a quite normal practice in writing iOS app, with regard to memory, how do I manage the objective-c data member in c++ class, 1) using ARC and 2) using MRC? In particular, is there any rule of thumb that I should know in order to correctly writing constructor and destructor for the c++ class that has objective-c member?
Yes, you can do this. It's not unusual.
In ARC: You just use it and it works. Note that if you put an Objective-C data member inside of a class with no constructors or destructors (a "POD" class), you will get a warning because bad things will happen if that definition is imported into both ARC and MRC code. The solution if that's the case is to add a dummy constructor or destructor.
In MRC: You need to retain and release it following normal MRC memory management rules for instance variables. i.e. if you assign to it, make sure to release the previous value and retain the new value. In the destructor of the class (add a destructor if there isn't already one), you need to release it. Also, in the constructor, make sure to initialize the object pointer (either to nil or some other value), because pointers in C/C++ are not automatically initialized.

Delphi - Accessing Object Instance Data from Another Object

I have my main form. Form_Main
It creates two instances of two classes.
Candle_Data : TCandle_Data;
Indicator_2700 : TIndicator_2700;
In order for Indicator_2700 to properly compute its values it must have access to the candle data in the obect Candle_Data from inside one of its methods. Thus how can Indicator_2700 access data inside Candle_Data? Does Form_Main have to pass it as a argument at Constructor time?
Both Class declarations are in their own unit file.
You could use any of the following (non-exhaustive) methods:
Pass the object reference as a parameter to any methods that need it. Of course you need to get hold of Candle_Data so the suitability of this approach really depends who the caller is.
Pass the Candle_Data object reference to the constructor of the other object and then store it in a private member field.
Make the object reference a public property of the single instance of the main form and access it that way.
We don't really have enough information to advise you which is best but the starting point is always to prefer parameters and local variables over global state.
TIndicator_2700 could have a property to link it to the instance of TCandle_Data that is relevant to its own instance or you should supply it as an argument to the method that needs to access the data.
You could certainly pass the TCandle_Data instance into the constructor of Indicator_2700, and store a reference within the resulting instance until you needed it.
Both class declarations are in their own unit file.
That suggests that both have nothing to do with the other. But still you want one to have knowledge about the other. It sounds like a little design mixup, but that doesn't need to be the case.
There are multiple solutions, here are three of them, each with its own purpose:
Place both classes in the same unit, only if both classes have a common theme/subject (e.g. TCar and TAirplane in the unit Transport),
Use one unit in the other unit, only if both units represent different subjects, but one may depend on the other (e.g. unit Transport uses unit Fuel: TCar needs TDiesel, but TDiesel doesn't need a TCar). This only works one-way. Delphi prevents using in both ways with a compiler error: "Circular unit reference to 'Fuel'". The only workaround is to use the second unit in the implementation section, but that usually is considered a big nono.
Declare a new base-class in a new unit, only if the base-class has a common subject, but the final descendants do not (e.g. TFuel is used by all transportation classes like TCar, TAirplane and THorse, but TFood (a descendant of TFuel) is only used by THorse and TPerson).
As for how to link both classes together, see the already given answers.

If everything implemented an interface, would this be garbage collection?

I'm still something of a newbie, and I know my thinking is incorrect; I just don't know where ...
Just about everything in Delphi is descended from TObject. What if everything instead descended from a TInterfaceObject that implemented some trivial interface (e.g., "INamable," with a single method that returned a class's name string)? Since TObject already has a property that returns a name string, you wouldn't need to add anything to additional classes.
In other words, a TInterfacedObject would inherit from TObject (or something high up in the hierarchy), and everything currently descending from TObject would now descend from this new class. Wouldn't this mean everything was now reference counted?
If you can spot where my knowledge is lacking, I'd love to learn. Thanks, as always -- Al C.
It's not clear whether you're asking:
Why didn't Borland do this, when they originally developed Delphi?
Why don't Embarcadero do this, in a future version of Delphi?
Why don't I do this, with my own user data types?
Wouldn't this mean everything was now reference counted?
Yes it would.
However, you don't necessarily want everything to be ref-counted: every little integer, every string, every boolean, every element in an array ... if for no other reason that the implementation of ref-counting adds some overhead, e.g. a little extra memory per object, perhaps insignificant for large objects but proportionally more significant if applied to every tiny object.
Also, see also Garbage Collector For Delphi Objects and Components which says (quote),
Delphi provides three ways of object management :
Create/destroy the objects using try..finally.
Use TComponent descendants - create a component and let its owner free it.
Interfaces - when the reference count for an interface becomes 0 the
object which implements it is
destroyed.
The Delphi help says you shouldn't mix
the TComponent owner approach with the
interface memory management, but ...
Would this be garbage collection?
Not quite; mere reference-counting isn't as robust as garbage-collection:
With reference-counting, if you have two reference-counted instances each holding a reference to the other, then they're not released automatically. To release them you would need to break this 'circular reference' (i.e. explicitly tell one of them to release its reference to the other).
With true garbage-collection, the garbage-collector would notice that those two istance aren't referenced from anywhere else, and release them both.
Update
If you annotate your potentially circular references as [weak] references, then they will get destroyed ok. But prior to Delphi 10.1 Berlin this only works in the NexGen compilers (i.e. those that use LLVM under the hood). From 10.1 Berlin onwards these [weak] references work everywhere.
It wouldn't be working garbage collection because interfaces use a very simple reference-counting system, and circular references, which are very common in Delphi code, break simple ref-counting.
No, because of two things:
Even if a class implements an interface it does not automatically make it reference counted. Only if you actually use it to implement that interface the reference counting will have any effect.
As others already said: Reference counting in interfaces will result in the class instance to be freed immediately when the reference count reaches 0. It is an implicit call to the Free method at that point in code. This will fail e.g. if two objects reference each other. True garbage collection will free the objects not when they go out of scope but when memory is needed, so there is no performance impact every time the reference count reaches 0 because the object will just continue to exist. In addition a good garbage collector will detect the isolated circular references (e.g. A references B references C references A but nothing else references any of these objects) and will free these objects as well.
Garbage collection is different from simple ref counting. You can have automatic deletion when a ref count reaches 0, but that too is not garbage collection. Garbage collection means letting go of your ability to control when things are deleted from memory, and allowing the underlying language's implementation to optimize the behviours. You stop paying attention to reference counts, and trust in the dynamic behaviours of a particular implementation of garbage collection.
Naturally, garbage collection uses a system of reference counting to know when something is no longer referenced, but that is a small piece of the puzzle.
Reference counting is a form of garbage collection, but not a very good one. It is used by some languages (python I think) although often with cycle detection.
Even if you descended from TInterfaceObject, the object is not reference counted and thus garbage collected unless you only use the interface reference and not the object reference.
I.e. you would need to use
Var
nameable: IMyInterface;
begin
nameable:= IMyInterface.Create();
nameable.x(y);
etc
end;
This implies that your interface needs to support already the methods and properies that you require which quickly becomes tedious as you need to create an interface for each class.
It can be done reasonably easily in D2009 or later though. See Barry Kelly's implimentation of smart pointers. The usual reference countng cavets apply though.

Where should a class free its private variables?

As there is no garbage collection in Delphi, where exactly do you unload variables?
Say I have a type with a set of private vars.
Would it suffice to have a Destroy method that does this work?
Do I need to explicitly call this destroy method in my consuming classes?
The best way to organize destruction in delphi is to always think about "who will create the given vars".
If you also free them in this context (For you private vars the destroy method of the class) it's much less likely that you will encounter memory leaks.
Actually the destructor of a class is normally not called via
myInstance.Destroy();
instead the typical way of doing it is via
FreeAndNil(myInstance);
or
myInstance.Free();
As delphi will handle calling the destructor method at order
Objects need to be destroyed when you are ready with them: using .Free (which calls the destructor .Destroy) or FreeAndNil.
If you are using interfaces: they are reference counted and hence they are freed for you. The same for strings.
Most functions that you need to pass an object do not take ownership of the object so you should free it afterwards when you are done with them. If you create components on a form, please note that they are objects, are owned by the form and you should let the form free them for you.
For example: in your TLight you create a TTimer probably without an owner. In this case you should Free the timer in the destructor of the TLight class. If your TLight was a TControl or TComponent itself you could have created the Timer with Self as the Owner and it was automatically freed when your TLight instance was freed.
That's how I see it:
Primitive types (like integer, real, double, extended), arrays, sets, records: they are automatically destroyed when out of scope.
Reference-counted types (strings, interfaces types, interface references): they are automatically destroyed when their reference counter is equal to zero.
Objects from classes that fall in one of those situations: does not descend from TComponent, are in list objects that do not implement ownership or are a TComponent descendant but does not have an owner assigned to it:
When their class descend from TInterfacesObject and are accessed from a interface reference: same behavior from reference-counter types (see above)
Other cases: call Object.Free or FreeAndNil(Object) to manually destroy it (in a try..finally structure would be even better)
Objects that have an owner (TComponent descendants or are in list objects that implement ownership): the owner will take of them in proper time.
I noticed the following comment from OP:
I have noticed the concept of owner.
Yet I couldn't pass my custom class to
the TTimer.Create() method as it is
expecting a TComponent. Why do they
restrict things to be used in forms
only? Doesn't that furhter petrify the
bad habit of putting logic in your
views (forms)?
See, a TComponent descendant can be registered on the pallete to have the ability to be used in design-time (for example, in a form) . But it's doesn't means it must!!
You can pass your custom-class to TTimer.Create() if it descends from TComponent but you don't need to instantiate it in design-time - or even be owned by a TForm descendant (if you want to manage it's lifetime, you don't even need an owner!).
Ownership is a mechanism it's to help people to save time....
You keep referring to a "type with private vars" and asking about "unloading variables." I'm going to go out on a limb (as I may be have misinterpreted your message), and presume you're talking about class variables and are asking about when these class variables should be finalized when the "class unloads." (You've been doing Java or .NET programming at some point, no ;-).
The key to what you're asking is a unit finalization section. The overall layout of a unit includes 4 overall sections, two of which are optional, initialization and finalization.
unit Foo;
interface
// put things here you want other units to see
implementation
// put the *implementation* of the things from the interface here along with things
// you only want this unit to see.
initialization
// <optional> put code here that you want to execute when this unit is "loaded"
finalization
// <optional> put code here that you want to execute when this unit is "unloaded"
end.
If you're talking about instance variables of a class type, then some of the other answers you've already gotten (and are bound to get) should shed some light on that.

Resources