The reference counting rules of the COM standard have three principles:
1. When a non-null interface pointer is copied from a memory location to another memory location, addref should be called to notify the object of additional references.
2. For memory locations that already contain non-null interface pointers, you must call release before overwriting the memory location to notify the object that the reference has been destroyed.
3. If you have a special understanding of the relationship between two or more memory locations, the redundant addref and release calls can be optimized.
From these three principles, we come down:
When the addref method is called:
1. When writing a non-null interface pointer to a local variable.
2. When the caller writes a non-null interface pointer to the [out] or [In, out] parameter of the method or function.
3. When the called party returns a non-null interface pointer as the actual result of the function ..
4. When writing a non-null interface pointer to a data member of an object.
Call the release method:
1. rewrite a non-empty local variable or data member.
2. Before leaving the scope of a non-null local variable.
3. When the caller needs to rewrite the [In, out] parameter of the method or function, and the initial value of the parameter is not empty. (If the initial value of the parameter is null, you do not need to release it. Generally, if the input value of the [out] parameter is null, do not release the [out] parameter .)
4. Rewrite the non-empty data member of an object.
5. before leaving the destructor of an object, there is a non-null interface pointer as a data member.
Exceptions:
When the caller passes a non-null interface pointer to a function or method through the [in] parameter, neither addref nor release needs to be called.