分配自我的后果

发布于 2024-08-27 16:06:44 字数 331 浏览 10 评论 0原文

今天发现一段代码,我觉得有点臭……

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秉烛思 2024-09-03 16:06:45

是的,你可以使用 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)

流心雨 2024-09-03 16:06:44

您可以分配给 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.

不乱于心 2024-09-03 16:06:44

考虑一下方法相当于一个自由例程,接受对象作为其名为 Self 的第一个参数

TMyClass.MyRoutine({args})  <=>  MyRoutine(Self: TMyClass {; args})

考虑到这一点,您会发现您可以在本地更改 Self 的内容,而不会损坏原始内容对象。

但你是对的,它确实并且很容易出错。

如果评论中没有非常有力的令人信服的案例,我不会接受这样的代码......

Consider that a method is equivalent to a free routine accepting the Object as its 1st parameter named Self:

TMyClass.MyRoutine({args})  <=>  MyRoutine(Self: TMyClass {; args})

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文