在Delphi中记录方法和常量参数 [英] Record methods and const parameters in Delphi

查看:660
本文介绍了在Delphi中记录方法和常量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p


records-with-methods p>以前没有尝试滥用 const 惯例,我有点惊讶于
找到编译器接受的代码:

  type 
TTest = record
Field:String;
程序更新;
结束

程序TTest.Update;
begin
Field:= Field +'+1';
结束

程序DoStuff(const t:TTest);
begin
ShowMessage(t.Field);
t.Update;
ShowMessage(t.Field);
结束

如果您尝试执行
t.Field: ='doh'; 在DoStuff fi中,编译器会正确抱怨,但是您可以调用修改const记录的方法,甚至没有提示或警告。因此,这是不同于引用类型(如类或动态数组)的行为,其中允许直接字段写入(因为const仅限制参数本身的更改)。



附录:这样可以通过这种方式修改声明的编译时常数,如:

  const 
cTest:TTest =(Field:'1');
...
cTest.Update; //将显示'1',然后'1'+'1'
ShowMessage(cTest.Field); //将显示'1'(因为在编译时被优化)

这是一个被接受/记录的行为?或只是编译器的缺点?

解决方案

const 在Delphi中的方法调用,无论是记录还是类的实例。所以我不认为方法调用的处理方式是不一致的。



如果方法不能被作为一个 const传递的记录调用参数,那么这几乎可以使用无用的方法渲染记录。这意味着,例如,不能调用属性getter。为了对 const 传递的记录进行限制,需要与C ++的const成员函数有一个等价的概念。这将允许编译器知道某些方法是非突变的。


It looks like the Delphi compiler does not honor const record parameters when "records-with-methods" are involved.

Having not tried to abuse the const convention previously, I was a little surprised to find the compiler accepted code like that:

type
    TTest = record
       Field : String;
       procedure Update;
    end;

procedure TTest.Update;
begin
    Field := Field + '+1';
end;

procedure DoStuff(const t : TTest);
begin
    ShowMessage(t.Field);
    t.Update;
    ShowMessage(t.Field);
end;

While if you try to do a t.Field:='doh'; in DoStuff f.i., the compiler will properly complain, but you're allowed to call methods that modify the "const" record without even a hint or warning. So this is different behavior than for reference types (such as classes or dynamic arrays), where direct field writes are allowed (as const only restricts changes to the parameter itself).

Addendum: this allows to modify declared compile-time constants this way too, as in:

const
   cTest : TTest = (Field : '1');
...
cTest.Update;              // will show '1' then '1'+'1'
ShowMessage(cTest.Field);  // will show '1' (because optimized at compile-time)

Is that an accepted/documented behavior? or just a compiler shortcoming?

解决方案

const never places any restrictions on method calls in Delphi, be they on records or instances of classes. So I don't think there is anything inconsistent with the treatment of method calls.

If methods could not be called on record passed as a const parameter, then that would pretty much render records with methods useless. It would mean, for example, that a property getter could not be called. In order to place restrictions on such records passed as const, there would need to be an equivalent concept to the const member functions of C++. That would allow the compiler to know that certain methods were non-mutating.

这篇关于在Delphi中记录方法和常量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆