How to check if my object is configured correctly?

I wonder if there is a "trick" that allows you to find out if the (used) used objects were correctly used in part of the code, or, in other words, does not create a memory leak.

Say I have a container for GDI objects (or another that I need to explicitly delete)

public class SuperPen { Pen _flatPen, _2DPen, _3DPen; public SuperPen() { _flatPen = (Pen)Pens.Black.Clone(); _2DPen = (Pen)Pens.Black.Clone(); _3DPen = (Pen)Pens.Black.Clone(); } } 

Now that I need to delete the GDI objects, I:

 public class SuperPen : IDisposable { Pen _flatPen, _2DPen, _3DPen; public SuperPen() { _flatPen = (Pen)Pens.Black.Clone(); _2DPen = (Pen)Pens.Black.Clone(); _3DPen = (Pen)Pens.Black.Clone(); } public void Dispose() { if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; } // HERE a copy paste 'forget', should be _2DPen instead if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; } if (_3DPen != null) { _3DPen.Dispose(); _3DPen = null; } } } 

A situation like this can happen if you add a new β€œdisposable” object and forget to dispose of it, etc. How can I detect my mistake, I mean, check if my SuperPen was configured correctly?

+4
source share
4 answers

Do not think it is possible; the best you can do is get a profiler (like ants profiler ) and measure it. If you find that you are leaking memory excessively (through the profiler), then something is wrong.

Besides using a profiler, I'm not sure about any automatic methods that will help you identify unallocated resources.

+2
source

A tool such as MemProfiler or ANTI Memory Profiler will identify memory leaks (both have trial versions).

+1
source

I would suggest using this pattern , which includes a destructor, to ensure that unnecessary elements are cleared. This will catch everything that you do not call "dispose", and is a sure failure.

0
source

I believe that FxCop (available standalone or integrated in the Team System VS2005 + version) will detect this.

0
source

Source: https://habr.com/ru/post/1300080/


All Articles