简体   繁体   中英

Using unique_ptr and shared_ptr with function parameters in C++

I'm calling Windows functions like GetExplicitEntriesFromAcl that dynamically allocate memory (arrays) on my behalf whose memory must be freed with a call to LocalFree.

ULONG EntryCount;
EXPLICIT_ACCESS* pItem = nullptr;
ULONG EntryCount;
status = GetExplicitEntriesFromAcl(pACL, &EntryCount, &pItem);
...
...
LocalFree(pItem);

Can I declare pItem to be an instance of std::shared_ptr and still have GetExplicitEntriesFromAcl allocate it for me?

How?

You have to create a custom deleter so that std::unique_ptr and std::shared_ptr know the special way to delete the memory. Something like this:

struct explicit_access_deleter
{
    void operator()(EXPLICIT_ACCESS* pItem) const
    {
        if(pItem)
            LocalFree(pItem);
    }
};

Then you can provide maker functions to call the allocation function and use your special deleter:

std::unique_ptr<EXPLICIT_ACCESS, explicit_access_deleter>
    make_explicit_access_unique_ptr(ULONG EntryCount)
{
    EXPLICIT_ACCESS* pItem = nullptr;
    int status = GetExplicitEntriesFromAcl(pACL, &EntryCount, &pItem);
    // do some error checking here ...
    return std::unique_ptr<EXPLICIT_ACCESS, explicit_access_deleter>(pItem);
}

std::shared_ptr<EXPLICIT_ACCESS>
    make_explicit_access_shared_ptr(ULONG EntryCount)
{
    return make_explicit_access_unique_ptr(EntryCount);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM