user3667089 user3667089 - 8 months ago 46
C++ Question

How to convert a function that returns unique_ptr into raw pointer?

Suppose there is a function in a legacy library that I want to use that requires a function pointer as an input

void LegacyFunction(int* (*func)(float, float), int a, float b);

but the problem is it is expecting the return value of the function to be an int raw pointer instead of an int unique_ptr, meaning I can only get it to compile if my function looks like

int* MyFunc(float a, float b);

in other words, if I modify MyFunc into

std::unique_ptr<int> MyFunc(float a, float b);

and pass it into the legacy library function like

LegacyFunction(MyFunc, 1, 2.0f);

there will be a compilation error. I know if the function is taking an usual int pointer there can be some workaround using the
function like

std::unique_ptr<int> a;
LegacyFunctionRawPointer(a.get(), 1, 2.0f);

Is there a similar workaround for function pointer input? It will be a travesty if I have to replace the unique_ptr for MyFunc with raw pointer.


A lambda function should work, e.g.:

LegacyFunction([](float a, float b) { return MyFunc(a, b).release(); }, 1, 2.0f);

but only if LegacyFunction will naturally delete/free the memory that MyFunc allocated with the appropriate operation (so if MyFunc used new int, LegacyFunction must use delete retval;; if it used new int[x], it must use delete[] retval;).

The release method gets the contained pointer and relinquishes ownership, so you've explicitly given up unique_ptr's protections; not a great idea if you can avoid it.