Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any advantages of using std::unique_ptr<T>& instead of std::unique_ptr<T>?

Tags:

c++

unique-ptr

Are there any advantages of using std::unique_ptr<T>& instead of std::unique_ptr<T>? For example, in function arguments?

like image 998
InFamous X Avatar asked Dec 05 '22 11:12

InFamous X


1 Answers

There are a few different situations

  1. You want to transfer ownership to the function
    • Use std::unique_ptr<T>
  2. You want to allow the function to modify the pointer
    • Use std::unique_ptr<T> &
  3. You want to allow the function to modify the pointee
    • Use T &, and dereference at the call site
    • If the pointer may be null, instead use T * and call unique_ptr::get at the call site
  4. You want to allow the function to observe the pointee
    • Use const T &, and dereference at the call site
    • If the pointer may be null, instead use const T * and call unique_ptr::get at the call site
  5. You want to allow the function to have a copy of the pointee
    • Use T, and dereference at the call site
  6. You have a ranged-for loop (or <algorithm> call) over a collection of unique_ptr<T>, and want to observe the values, and don't have ranges::indirect (or similar)
    • Use auto &, and know that it is inferred as std::unique_ptr<T> & (or const std::unique_ptr<T> & if the collection is const), so you have to dereference in the loop body
like image 135
Caleth Avatar answered Feb 16 '23 04:02

Caleth