Home c++ Do you have a memory leak when calling CCOMPTR and QUERYInterface?

Do you have a memory leak when calling CCOMPTR and QUERYInterface?

Author

Date

Category

Tell me, does this code have the right to exist or not?

HRESULT CMYCLASS :: ASSIGN (IUNKNOWN * SRC) {
  if (! src)
    Return E_Invalidarg;
  HRESULT RES;
  ATL :: CCOMPTR & LT; IADDRESS & GT; ADDR;
  res = src- & gt; QueryInterface & lt; iaddress & gt; (& amp; addr);
  If (succeeded (res))
    Return Addr- & GT; GetStreet (* this- & gt; Street);
  ELSE.
    RETURN RES;
}

What confuses me. In the CBasePtr class designer, which is the parent class for the CCOMPTR class, I see the addref () call. But QueryInterface , in theory, it already causes addref () , i.e. Get a memory leak. Or because In the queryInterface a pointer is transmitted, then the additional addref () will not be called?


Answer 1, Authority 100%

Basic class for CCOMPTR I have a CComptrBase in VS2017. Here is its designers (from atlcomcli.h):

compthrbase () throw ()
{
  p = null;
}
COMPTRBASE (_inout_opt_ T * LP) Throw ()
{
  p = lp;
  if (p! = NULL)
    p- & gt; addref ();
}

As can be seen, there is a AddRef call here, but only in the designer with the parameter. This constructor would be called in the code of the type atl :: CCOMPTR & LT; IADDRESS & GT; ADDR (SomePointer); . In your case, the constructor is called without a parameter, and then an address from QueryInterface is recorded in an empty CCOMPTR instance. Addref will be called only once (in QueryInterface).

Say, whether there is a memory leakage, according to the above incomplete code it is impossible. If the method is transferred to the correct implementation of IUNKNOWN, it should not be, in the sense that there is nothing to cause memory leakage in this code. If there is a memory leak in your real code, you can learn using the debugger by putting the stop point to the Release method in the COM object. If everything is fine, with the last call, the Release reference meter must be zero.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions