3

I have a pointer to a COM object (in C++). Is there a way to get the current reference count of the object which the pointer is pointing to?

Brahmaprasad R
  • 131
  • 2
  • 9
  • 1
    I can't think of a situation where you would need to know. That's the whole point of reference-counted objects. – paddy Jun 08 '15 at 07:59
  • Reference counting is responsibility of called object (within `AddRef` and `Release` of `IUnknown`). `AddRef` returns actual count (even if you're _warned_ to use it only for test purposes) then the only thing you may do is to wrap `IUnknown` within a custom `ObjectFactoryWithReferenceCounting` where you keep track of them...tedious, at best (and tricky to make it thread-safe). – Adriano Repetti Jun 08 '15 at 08:02
  • @AdrianoRepetti: I don't think that's correct. You need to count `AddRef`'s via any interface, including interfaces you don't even hold (the object may be shared). – MSalters Jun 08 '15 at 09:20
  • @MSalters I agree, it works only if you own them and/or you can change their interface. – Adriano Repetti Jun 08 '15 at 10:06
  • 16
    @paddy Can't think of a situation where you'd need to know? Seriously? How about debugging? How about object tracking / usage? Yes - there can be temporary context level references but it can be useful if you ever write code that's more complex than Hello World and you want some more info. Anything in non-managed code (ie. C++) can easily be broken by not adding/releasing references or by not using smart objects, particularly when working in a team of inexperienced coders that may forget the rules. The question is valid. Don't assume anything. – mysticcoder Jan 19 '17 at 06:09

1 Answers1

9

Call IUnknown::AddRef and then immediately IUnknown::Release. The value returned by the latter is current count of outstanding references. Note that the value does not have to be accurate, it is informational only.

Roman R.
  • 68,205
  • 6
  • 94
  • 158