简体   繁体   English

将unique_ptr传递给库函数(FORTRAN函数)

[英]Passing unique_ptr to library functions (FORTRAN function)

I am using LAPACK library to create a R-package using C++. 我正在使用LAPACK库来使用C ++创建R包。 I am using unique_ptr for defining the arrays as 我使用unique_ptr将数组定义为

   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 然后我将此unique_ptr传递给库函数(FORTRAN函数),该函数接受指向double数组的指针,并将函数内的此数组更新为

   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. 浏览完网页后,我注意到不建议将unique_ptr作为指针参数传递给函数。 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. 假设该库不会取得数组的所有权并尝试delete它本身,我认为这是完全正常的。

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. 您通常应该更喜欢通过引用或原始指针传递,并且通常只在传输所有权时传递unique_ptr ,所以我认为这是正确的。 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. 您知道在函数调用之后,当unique_ptr超出范围时,数组将不会被删除,这正是您想要的。

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. 有关如何传递(智能)指针的摘要,请参阅GotW#91

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. 如果库在函数调用之后保留了指针,则必须确保unique_ptr在库完成使用之前不会超出范围,这有点棘手。

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. 他们完成后delete对象。 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. 这在C ++ 11中通常被认为是不好的做法,但是如果你需要调用这样的库,你不应该使用unique_ptr因为你不想自己delete对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM