KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Should the compiler hint/warn when passing a new instance of an object to a method having a const interface parameter of an interface that the object's class implements? Edit : The sample of course is simple to illustrate the issue. But in real life it gets way more complex: What if the creation and usage is in code that is far apart (different units, different classes, different projects)? What if it is maintained by different people? What if a non-const parameter becomes a const one, and not all calling code can be checked (because the person changing the code does not have access to all calling code)? Code like below crashes, and it is very hard to find the cause. First the log: 1.Run begin 1.RunLeakCrash 2.RunLeakCrash begin NewInstance 1 AfterConstruction 0 3.LeakCrash begin _AddRef 1 4.Dump begin 4.Dump Reference=10394576 4.Dump end _Release 0 _Release Destroy BeforeDestruction 0 3.LeakCrash Reference got destroyed if it had a RefCount of 1 upon entry, so now it can be unsafe to access it _AddRef 1 4.Dump begin 4.Dump Reference=10394576 4.Dump end _Release 0 _Release Destroy BeforeDestruction 0 3.LeakCrash end with exception 1.Run end EInvalidPointer: Invalid pointer operation Then the code that prematurely releases the object instance implementing an interface: //{$define all} program InterfaceConstParmetersAndPrematureFreeingProject; {$APPTYPE CONSOLE} uses SysUtils, Windows, MyInterfacedObjectUnit in '..\src\MyInterfacedObjectUnit.pas'; procedure Dump(Reference: IInterface); begin Writeln(' 4.Dump begin'); Writeln(' 4.Dump Reference=', Integer(PChar(Reference))); Writeln(' 4.Dump end'); end; procedure LeakCrash(const Reference: IInterface); begin Writeln(' 3.LeakCrash begin'); try Dump(Reference); // now we leak because the caller does n
Tags (comma-separated)
Save Edits
Cancel