问题
Given the following answer to a related question (https://stackoverflow.com/a/22086392/1420752) are objects reference counted in Windows-targeted Delphi applications?
I.e.:
Q1A does the following object have a reference count of 2 after the second statement?
o1 := TMyObject.Create;
o2 := o1;
Q1B Following on from the above, will assigning o1 to nil drop the reference count to 1?
o1 := nil;
Q1C Again following on, will assigning o2 to nil drop the reference count to 0?
o2 := nil;
Q1D Moving forward, if the above is correct and the object now has a reference count of 0, I understand that the compiler will NOT automatically free the object (o2.Free should have been called prior to o2 := nil above in order to prevent a memory leak). Remember I'm talking about a Windows target, not a mobile target with automatic reference counting (ARC).
Q1E If reference counting does not automatically free the memory associated with an object, then what precisely is the point of reference counting in Delphi (e.g., is it to help trace memory leaks)?
回答1:
Object instances are not reference counted under any desktop platform, including Windows. Objects are reference counted only under mobile platforms (iOS, Android). So questions Q1A-E are moot.
回答2:
As Uli already said, in the desktop compilers, objects are not reference counted. But in the mobile compilers they are, and the answers to your questions for those compilers would be:
- Q1A: yes, it would be 2
- Q1B: yes, it would be down to 1
- Q1C: yes, it would be 0 and the object would be freed automatically
- Q1D: see Q1C
- Q1E: See Q1C
Note that interfaces (and thus the objects implementing them) are refcounted, even in the desktop compilers. The above answers also apply to such interfaces.
来源:https://stackoverflow.com/questions/22088170/are-objects-reference-counted-in-windows-targeted-delphi-applications-and-if-so