tache
tache

Reputation: 183

MSXML get_documentElement() & returning pointers to COM interfaces

I was wondering if it is standard practice in COM libraries to call Addref on an COM interface, that is returned from a function. For instance:

IXMLDOMElement* domElement = NULL;
document_->get_documentElement(&domElement);  // does get_documentElement() call Addref on domElement?
// ...
// do something with domElement
// ..
domElement.Release(); // correct?
// (btw. member variable document_ is of type CComPtr<IXMLDOMDocument2>

or with a smart pointer:

CComPtr<IXMLDOMElement> domElement;
document_->get_documentElement(&domElement);

Btw. I found that in the docs of MSXML for "Windows media 9 series" it says that Addref is called: http://msdn.microsoft.com/en-us/library/ms751196(v=vs.85).aspx

But in the official documentation nothing is mentioned about it: http://msdn.microsoft.com/en-us/library/ms759095(v=vs.85).aspx

Upvotes: 0

Views: 952

Answers (2)

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15261

Yes you are supposed to addref before returning a COM object, as the caller is going to have an new interface pointer referencing the object, so the reference count needs to be increased by one. This is the rule, not the exception.

Documenting the internal addref is the exception, however, as reference counting is one of the fundamentals of COM. Probably the documentation was written when a lot of callers of this method don't know the rule and caused too many memory leaks.

When you, as a caller, no longer need the received object, you need to call Release directly or indirectly (e.g. through a class destructor), and stop using the reference pointer (many people set the pointer to null to prevent dangling pointers).

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595320

The function that returns an interface pointer must call AddRef() on it before exiting, not the function that is receiving the object. The function that receives the interface pointer must use it as-is and then call Release() on it. Which means that get_documentElement() will call AddRef(), so do not call it yourself.

The rules for who - the caller or the callee - is responsible for doing what in regards to reference counting and memory management in COM are clearly defined in COM's documentation on MSDN:

The Rules of the Component Object Model

Reference Counting Rules

Upvotes: 2

Related Questions