0

I'm trying to use a unique ptr in the following scenario:

MyClass *pMC = NULL;
if ( !MyCustomAlloc(void ** (&pMC), sizeof(MyClass) )
{
    return false;
}
// do things
if (something else fails)
{
    MyCustomDelete(pMC);
    return false;
}

Now, what I'm trying to do is have convert this to a unique ptr so that the MyCustomDelete doesn't need to be called explicitly.

What I don't get is how I can retain the above structure and still return the appropriate values.

unique_ptr<MyClass, void (*)(void**, size_t)> pMC( <b>Not Sure What Goes Here</b> , MyCustomDelete);
  • If I put MyCustomAlloc as the 1st arg, how will it's failure be detected?
  • Or if I do the following then pMC will be initialized to NULL, but how can the custom deleter be set? unique_ptr<MyClass, void (*)(void**, size_t)> pMC;

    Can I do something like pMC.set(MyCustomDelter)?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • `MyCustomAlloc(void ** (&pMC), sizeof(MyClass)` leads to undefined behaviour in Standard C++ (you cannot alias some other pointer as `void *`) . It would be better to make the function be `template T *MyCustomAlloc();` or similar – M.M Aug 09 '18 at 03:03
  • Have you tried the suggestion [here](https://stackoverflow.com/questions/19053351/how-do-i-use-a-custom-deleter-with-a-stdunique-ptr-member) ? – M.M Aug 09 '18 at 03:04
  • Thanks. Trying it out. Will report how it goes. – fastforward Aug 09 '18 at 04:12

1 Answers1

0

The solution is to create a delete class which overloads the () operator and then pass this class as the 2nd template argument.

typedef struct MyClassDeleter { void operator()(MyClass* p) { MyCustomDelete(p); } } std::unique_ptr<MyClass, MyClassDeleter> pMC;