Passing unique_ptr to library functions (FORTRAN function)
I am using LAPACK library to create R package using C ++. I am using unique_ptr to define arrays as
unique_ptr<double[]> my_arr(new double[arr_length]);
Then I pass this unique_ptr function to a library (FORTRAN function) which takes a pointer to a double array and updates that array inside the function as
F77_CALL(daxpy) (&num_feat_, &beta, tmp, &inc_one, my_arr.get(), &inc_one);
After going over the net, I noticed that it is not recommended to pass unique_ptr as a function pointer argument. However, the library functions I am using need a pointer in their argument. I cannot free the pointer before sending it to the function, since the library function needs to update the pointer. Is there an efficient way to handle this?
source to share
Assuming the library won't take responsibility for the array and give it a try delete
, I think it's fine.
You usually prefer to pass by reference or raw-pointer and usually skip unique_ptr
when you pass ownership, so I believe this is correct. The calling code retains unique ownership of the array.
You know that the array will not be deleted until after the function call, when unique_ptr
out of scope, what exactly you want.
I think this is the correct way to call functions that are not going to take over, even if they are in your own code.
See GotW # 91 for a summary on how to pass (smart) pointers.
If the library retained the pointer after calling the function, you would need to make sure unique_ptr
not out of scope before the library finishes using it, which is a little more complicated.
There are several libraries that assume that you will allocate objects on the heap and pass them to their owners via a raw pointer (I've seen it in some rendering libraries). They are delete
an object when they are done. This is generally considered bad practice in C ++ 11, but if you need to call libraries like this you shouldn't use unique_ptr
, since you don't want the delete
object yourself.
source to share