Reputation: 705
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?
Upvotes: 1
Views: 141
Reputation: 48605
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);
}
Upvotes: 4