[英]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
以使图片消失。
Visible
to true
when you want to display the next image. Visible
还原为true
。 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: 封装属性分配具有两个优点:
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.