分配自我的后果
今天发现一段代码,我觉得有点臭……
TMyObject.LoadFromFile(const filename: String);
begin
if fileExists(filename) then
self := TSomeObjectStreamer.ReadObjectFromFile(filename);
end;
如果这段代码有效,它至少会泄漏一些内存,但是它有效吗?
以这种方式分配给 self 可以吗?
如果流式对象与原始对象属于不同的子类怎么办?
如果流式传输的对象属于不同的类,并且与原始对象没有共同的祖先怎么办?
Found a piece of code today, that I find a little smelly...
TMyObject.LoadFromFile(const filename: String);
begin
if fileExists(filename) then
self := TSomeObjectStreamer.ReadObjectFromFile(filename);
end;
If this code works, it will at least leak some memory, but does it work?
Is OK to assign to self in this manner?
What if the streamed object is of a different subclass then the original self?
What if the streamed object is of a different class with no common ancestor to the original self?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以使用 self 作为局部临时变量,即使它在这里没有用。
但在这种情况下,流式对象必须与 self (TMyObject) 属于同一类,否则编译器将检测到错误,因为类型不兼容。
在您的示例中,
TSomeObjectStreamer.ReadObjectFromFile()
应该返回 TMyObject 或者您的编译器应该警告您(或抛出错误)yes, you can use self as a local temporary variable, even if it is useless here.
But the streamed object must be the same class as the self (TMyObject) in this case, or the compiler will detect an error, because type are not compatible.
In your example,
TSomeObjectStreamer.ReadObjectFromFile()
should return a TMyObject or your compielr should warn you (or throw an error)您可以分配给 Self,但它只是一个局部变量,您实际上不会更改任何内容超出该方法的范围。 因此,该代码几乎肯定不会执行原始编码器显然认为它会执行的操作。
You can assign to Self, but it's only a local variable and you won't actually change anything outside the scope of that method. So that code is almost certainly not going to do what the original coder apparently thinks it's going to do.
考虑一下方法相当于一个自由例程,接受对象作为其名为 Self 的第一个参数:
考虑到这一点,您会发现您可以在本地更改 Self 的内容,而不会损坏原始内容对象。
但你是对的,它确实臭并且很容易出错。
如果评论中没有非常有力的令人信服的案例,我不会接受这样的代码......
Consider that a method is equivalent to a free routine accepting the Object as its 1st parameter named Self:
With that in mind, you see that you can locally change the content of Self without damaging your original Object.
But you are right it is really smelly and very much prone to error.
I would not accept code like that without a very strong convincing case in a comment...