An assignment of a record variable on a non-by-reference type should give a warning. Don't you think?

An assignment of a record variable on a non-by-reference type should give a warning. Don't you think?

RWithPointers = record
Name: string;
Plugin: TSomeElaborateClass;
class procedure Clean(aInstance: RWithPointers);
//class procedure Clean(var aInstance: RWithPointers); static;
end;

Will not work. But compiles w/o warnings.

Need a 'var' parameter:
class procedure Clean(var aInstance: RWithPointers);

Body:
class procedure RWithPointers.Clean(aInstance: RWithPointers);
begin
// Assigments of members on local variable (going out of scope)... Hey compiler!
aInstance.Name := '';
aInstance.Plugin := nil;
end;

Just asking. Bit me again. Stupid, i know.

Comments

  1. It probably should, yes. The compiler could easily check that this code has no effect. Actually, that's not strictly true: Assigning an empty string to Name will decrement the reference count of the original string.

    ReplyDelete
  2. Thomas Mueller Wow! That sound like ARC... having to prepend all and everything with [weak] or some such.

    But does the statement not still hold true? Even if there is a reference that decreases it does not ACTUALLY change the content of the record after the procedure has finished.

    ReplyDelete
  3. The compiler does what you tell it to do. Maybe a hint could be emitted in some cases.

    ReplyDelete
  4. Certainly should not be an error. A hint perhaps.

    ReplyDelete
  5. there's no reason you could not use the parameter to store temporary data. TRect is often used that way.

    ReplyDelete
  6. Hallvard Vassbotn, David Heffernan i wrote "warning". Should have written "hint"?
    Paul TOTH of course, that is useful and logical. Should have said "Not the result i wanted" instead of "not work". I would never want to change the behaviour of the resulting code.

    ReplyDelete
  7. Dany Marmur I understand, I would also like that Delphi puts a warning on each of my bugs :)

    ReplyDelete
  8. Paul TOTH Yes, it is often doen that way, but I personally find re-using parameters for temporary storage bad practice. A variable (and even more a parameter) should be for one single purpose, and re-using them for a different purpose is not good practice.

    But otherwise, I am not even sure if it should be a hint. If you don't want to write to the parameter, make it const. Otherwise you should be able to, and it is not uncommon to give a plain value parameter a new value in the course of a function or procedure, e.g. `S := Trim(S);` or similar. You don't want to get a hint, nor do you want that to have any side effects.

    ReplyDelete

Post a Comment