Home > Blockchain >  What's the use of casting a pointer to (Derived*) right before assigning it to a variable of ty
What's the use of casting a pointer to (Derived*) right before assigning it to a variable of ty

Time:03-13

What's the use of the static_cast<IDropSource*> in this piece of code (taken from here):

HRESULT CDropSource::QueryInterface(REFIID riid, void **ppv){
    IUnknown *punk = NULL;
    if (riid == IID_IUnknown) {
        punk = static_cast<IUnknown*>(this);
    } else if (riid == IID_IDropSource) {
        punk = static_cast<IDropSource*>(this);
    }
    
    *ppv = punk;
    if (punk) {
        punk->AddRef();
        return S_OK;
    } else {
        return E_NOINTERFACE;
    }
}

I fail to see what's the purpose of casting this to IDropSource* if it's going to be assigned to a variable of type IUnknown*.

Does this make any difference when later calling punk->AddRef()?

CodePudding user response:

the source's link is old cpp (since 2004)https://gcc.gnu.org/releases.html I think the g at that time have some difference operation like now, but after read the piece of code I saw its purpose is

only handle CDropSource::QueryInterface based on some case of riid

if (riid == IID_IUnknown) {

} else if (riid == IID_IDropSource) {

if the static_cast make this pointer = nullptr -> don't handle and return E_NOINTERFACE

if (punk) {
    punk->AddRef();
    return S_OK;
} else {
    return E_NOINTERFACE;
}

at that time, I assume that static_cast is quite similar to dynamic_cast of new gcc

to verify you need to get exactly what gcc used for test the static_cast operation

refer how dynamic_cast work : Regular cast vs. static_cast vs. dynamic_cast
PS: I can't find any information about what gcc version release dynamic_cast feature

CodePudding user response:

My personal feeling is that the purpose of casts is to add reference counts to different interfaces

  • Related