Where to put the destructor code for an ATL COM object?
Asked Answered
A

2

6

Where does the destructor code for things I have defined in an ATL COM object belong?

Should it go in ~MyComClass() or in MyComClass::FinalRelease()?

Ascariasis answered 16/2, 2012 at 15:38 Comment(0)
R
12

As long as FinalRelease is in question, I assume your question is related to ATL.

In most cases you can clean things up in either of the two. FinalRelease will be called immediately before the actual destructor. The important difference is that if you aggregate other objects, FinalRelease gives you a chance to clean the references and release dependencies before actual destructor of top level COM object class (esp. CComObject) starts working.

That is, you clean things up in two steps, first references to aggregated objects in FinalRelease and then other things in either FinalRelease or destructor.

Riot answered 16/2, 2012 at 16:6 Comment(0)
F
1

This is the general approach:

MyComClass::~MyComClass()
{
    // Cleanup object resources in here.
}

ULONG __stdcall MyComClass::Release()
{
    ref_count_--;

    if (0 == ref_count_)
    {
        delete this;
        return 0;
    }

    return ref_count_;
}

EDIT: FinalRelease() appears to be related to ATL which I am unfamiliar with.

Fitly answered 16/2, 2012 at 15:50 Comment(4)
Than you. The ATL wizard has not added a ::Release() method to my class, yet presumably this reference counting is going on somewhere? How can I find it?Ascariasis
@SideshowBob, sorry but I have never used the ATL wizard so I cannot comment on what it does. Roman R. seems to be familiar with it given his answer.Fitly
ATL generally uses new CComObject<T>, which inherits from T and adds implementations for AddRef and Release in the most derived class -- this way, the delete this; works correctly with a non-virtual destructor.Whitecollar
You should never implement Release() manually, when you are using ATL. As Simon Richter wrote, it is implemented by CComObject<T>.Debate

© 2022 - 2024 — McMap. All rights reserved.