Know what references an object

I have an object which implements reference counting mechanism. If the number of references to it becomes zero, the object is deleted.

I found that my object is never deleted, even when I am done with it. This is leading to memory overuse. All I have is the number of references to the object and I want to know the places which reference it so that I can write appropriate cleanup code.

Is there some way to accomplish this without having to grep in the source files? (That would be very cumbersome.)


A huge part of getting reference counting (refcounting) done correctly in C++ is to use Resource Allocation Is Initialization so it's much harder to accidentally leak references. However, this doesn't solve everything with refcounts.

That said, you can implement a debug feature in your refcounting which tracks what is holding references. You can then analyze this information when necessary, and remove it from release builds. (Use a configuration macro similar in purpose to how DEBUG macros are used.)

Exactly how you should implement it is going to depend on all your requirements, but there are two main ways to do this (with a brief overview of differences):

  • store the information on the referenced object itself
    • accessible from your debugger
    • easier to implement
  • output to a special trace file every time a reference is acquired or released
    • still available after the program exits (even abnormally)
    • possible to use while the program is running, without running in your debugger
    • can be used even in special release builds and sent back to you for analysis

The basic problem, of knowing what is referencing a given object, is hard to solve in general, and will require some work. Compare: can you tell me every person and business that knows your postal address or phone number?

Need Your Help

Read a record selected in DataGridView table and read through info of that record into fields that is not shown in the table

c# winforms visual-studio datagridview .net-3.5

Note: Some of the code included below has already been used in some of my other questions but regarding other issues. I have also edited most of the post to cause less confusion!