简体   繁体   English

尽管设置TImage :: Picture = NULL不会导致内存泄漏,但是有哪些替代方法可以避免这种混乱呢?

[英]Although setting TImage::Picture = NULL won't cause a memory leak, what alternatives exist that might avoid that confusion?

Despite bummi's fine explanation of why Image1.Picture := nil won't cause a memory leak , I'm concerned that it may raise red-flags in the minds of new people reading my code, since its safety is counter-intuitive. 尽管bummi很好地解释了为什么Image1.Picture := nil不会导致内存泄漏 ,但我担心它可能会在新人们阅读我的代码时引起危险,因为它的安全性违反直觉。 Therefore, I'd like to avoid it. 因此,我想避免这种情况。 What more-intuitive alternatives exist? 存在哪些更直观的选择? Although bummi's answer was for Delphi, I'm actually more interested in C++Builder. 尽管bummi的答案是针对Delphi的,但实际上我对C ++ Builder更加感兴趣。

The alternative is to use Image->Picture->Assign(NULL); 另一种方法是使用Image->Picture->Assign(NULL); , which is actually what Image->Picture = NULL; ,实际上是Image->Picture = NULL; does internally. 在内部执行。

I've set Image1.Visible to false to cause a picture to disappear. 我已将Image1.Visible设置为false以使图片消失。

  • Disadvantage: You'll have to restore Visible to true when you want to display the next image. 缺点:当您要显示下一张图像时,必须将Visible还原为true
  • Advantage: if you happen to want to display one particular image, but only at certain times, then toggling Visible could be more efficient than clearing and reloading. 优点:如果您碰巧只想显示一个特定的图像,但仅在特定时间显示,那么切换Visible可能比清除和重新加载更为有效。

If you're worried that the reader doesn't understand what image.Picture := nil; 如果您担心读者不明白什么image.Picture := nil; means, and you've established that that is the most straightforward way to clear an image, then add a comment stating what the property setter does. 意思是,您已经确定这是清除图像的最直接方法,然后添加注释以说明属性设置器的作用。

I don't necessarily agree that it needs any change at all, though. 不过,我不一定同意它根本不需要任何更改。 It's well-established that property setters can have side effects, and there is no convention in Delphi that after setting a property to a specific value, that re-reading that property will return that same value. 众所周知,属性设置器可能会产生副作用,Delphi中没有约定将属性设置为特定值后,重新读取该属性将返回相同的值。 In fact, in the VCL I suspect that properties that don't return the same value that was just set are more common. 实际上,在VCL中,我怀疑没有返回刚刚设置的相同值的属性更为常见。

Either way, comment or not, I would leave the assignment using nil exactly as it is. 无论哪种方式,无论是否发表评论,我都将使用nil原样。

Encapsulating the property assignment provides two advantages: 封装属性分配具有两个优点:

  1. a single location to document the non-leakiness of it ( DRY ) 记录单个位置的不泄漏( DRY
  2. a less worrisome-looking interface to use everywhere else 一个看上去不太烦人的界面,可以在其他地方使用

eg: 例如:

// Not a memory leak: see http://stackoverflow.com/a/23999207/782738
#define ClearImage(Image) Image->Picture = NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM