简体   繁体   中英

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(...) . I'm not clear on the best way to pass one of these objects to the process() function. 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);

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
  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

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

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

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

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

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.

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