I am using LAPACK library to create a R-package using C++. I am using unique_ptr for defining the arrays as
unique_ptr<double[]> my_arr(new double[arr_length]);
I then pass this unique_ptr to library function (FORTRAN function) which accepts pointer to double array and will update this array inside the function as
F77_CALL(daxpy) (&num_feat_, &beta, tmp, &inc_one, my_arr.get(), &inc_one);
After going through web, I noticed it is not recommended to pass unique_ptr as pointer argument to a function. However, the library functions I am using needs a pointer in their argument. I can not release the pointer before sending it to the function since the library function needs to update the pointer. Is there any efficient way to handle this?
Assuming the library is not going to take ownership of the array and try to delete
it itself I think this is perfectly fine.
You should generally prefer to pass by reference or raw-pointer and normally only pass unique_ptr
when you are transferring ownership so I think this is correct. The calling code retains unique ownership of the array.
You know the array will not be deleted until after the function call when the unique_ptr
goes out-of-scope which is exactly what you want.
I think this is the right way of calling functions that are not going to take ownership 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 the function call you would have to ensure the unique_ptr
did not go out-of-scope before the library finished using it which is a little more tricky.
There are some libraries that assume you will allocate objects on the heap and give them ownership via a raw pointer (I've seen it in some visualization libraries). They delete
the object when they are done. This is generally considered bad practice in C++11 but if you need to call such libraries you should not use a unique_ptr
as you don't want to delete
the object yourself.
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.