简体   繁体   English

传递unique_ptr作为参考参数或const unique_ptr参考

[英]Passing unique_ptr as reference parameter or const unique_ptr reference

I have some pool of objects that I maintain in a std::vector<std::unique_ptr<MyObject>> and I pass objects from this pool to a function void process(...) . 我在std::vector<std::unique_ptr<MyObject>>维护一些对象池,并将该池中的对象传递给函数void process(...) I'm not clear on the best way to pass one of these objects to the process() function. 我尚不清楚将这些对象之一传递给process()函数的最佳方法。 If I'm understanding the different answers and articles I've read it's best to pass this as a regular reference as follows: void process(MyObject& buffer); 如果我已经阅读了不同的答案和文章,那么最好将其作为常规参考传递如下: void process(MyObject& buffer);

From my understanding this is preferable because: 据我了解,这是可取的,因为:

  1. The buffer I'm passing in should be guaranteed to remain in existence throughout the lifetime of the process() method by virtue of the fact that it's called by the owner of the unique_ptr, ie the calling method 我要传递的缓冲区应确保在process()方法的整个生命周期中都存在,因为它是由unique_ptr的所有者调用的,即调用方法
  2. the caller can pass stack allocated objects as well so this doesn't impose allocation restrictions on clients of this method 调用者也可以传递堆栈分配的对象,因此这不会对该方法的客户端施加分配限制
  3. If the ptrs can be nullptr then it's advisable to pass a raw pointer to the process() method instead 如果ptrs可以为nullptr,则建议将原始指针传递给process()方法

Is this understanding or correct or what is the best guidance? 这是正确的理解还是正确的指导? Here are the references I've read: Passing const unique_ptr reference as parameter 这是我已阅读的参考:将const unique_ptr参考作为参数传递

https://www.chromium.org/developers/smart-pointer-guidelines https://www.chromium.org/developers/smart-pointer-guidelines

https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/

是的,出于您的原因,这是明智的做法。

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

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