Если бы все реализовало интерфейс, то это было бы сборкой "мусора"?

Следует иметь в виду, что "%d" будет только работать над 32 битами. Как только Вы начинаете использовать NSInteger для совместимости, если Вы когда-нибудь компилируете для платформы на 64 бита, необходимо использовать "%ld" в качестве спецификатора формата.

7
задан RRUZ 17 September 2009 в 00:31
поделиться

5 ответов

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 :

  1. Create/destroy the objects using try..finally.
  2. Use TComponent descendants - create a component and let its owner free it.
  3. 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.

8
ответ дан 6 December 2019 в 10:01
поделиться

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.

5
ответ дан 6 December 2019 в 10:01
поделиться

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.

2
ответ дан 6 December 2019 в 10:01
поделиться

Подсчет ссылок - это форма сборки мусора, но не очень хорошая. Он используется некоторыми языками (я думаю, python), хотя часто с обнаружением цикла.

Даже если вы произошли от TInterfaceObject, объект не подсчитывается по ссылкам и, следовательно, не собирается сборщик мусора, если вы не используете только ссылку на интерфейс, а не ссылку на объект.

Т.е. вам нужно будет использовать

Var 
  nameable: IMyInterface;
begin
  nameable:= IMyInterface.Create();
  nameable.x(y);
  etc
end;

. Это означает, что ваш интерфейс уже должен поддерживать необходимые вам методы и свойства, что быстро становится утомительным, так как вам нужно создать интерфейс для каждого класса.

Это можно сделать. достаточно легко в D2009 или новее. См. Использование Барри Келли интеллектуальных указателей . Тем не менее, применяются обычные справочные пещеры.

1
ответ дан 6 December 2019 в 10:01
поделиться

Нет, по двум причинам:

  1. Даже если Класс реализует интерфейс, он не делает его автоматически подсчитываемым. Только если вы действительно используете его для реализации этого интерфейса, подсчет ссылок будет иметь какой-либо эффект.
  2. Как уже было сказано другими: подсчет ссылок в интерфейсах приведет к немедленному освобождению экземпляра класса, когда счетчик ссылок достигнет нуля. неявный вызов метода Free в этой точке кода. Это не удастся, например, если два объекта ссылаются друг на друга. Настоящая сборка мусора освобождает объекты не тогда, когда они выходят за пределы области видимости, а когда требуется память, так что нет никакого влияния на производительность каждый раз, когда счетчик ссылок достигает 0, потому что объект просто продолжает существовать. Вдобавок хороший сборщик мусора обнаружит изолированные циклические ссылки (например, A ссылается на B, ссылается на C, ссылается на A, но ничто другое не ссылается на какие-либо из этих объектов) и также освободит эти объекты.
3
ответ дан 6 December 2019 в 10:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: