C++: Pass by shared_ptr, unique_ptr, raw pointer or reference?
Apart from the pass-by-value semantic, C++ provides different means of passing values to functions. Amongst others there are std::shared_ptr
, std::unique_ptr
, references and raw pointers. Because these four concepts are widespread and can potentially be used interchangeably, it’s useful to have clear guidelines in mind which one to prefer.
Given an object that shall be passed to a function, I came to the following conclusion:
- Function has no impact on the object’s lifetime → Pass by Reference
- In addition to (1) there’s a reason against using a reference → Pass by raw pointer
- Function prolongs the objects’s lifetime → Pass by
std::shared_ptr
- In addition to (3) the function is the object’s “end user” → Pass by
std::unique_ptr
.
Obviously there are exception. E.g. using raw pointers can still make sense in performance critical code. Also in case of (1), finding the right type of reference is another question.