This post is based on a post from Herb Sutter.
When
if (The ownership of the object isn't shared or moved && The lifetime of the object is guaranteed 1) { Pass the object itself by value, raw pointer or reference } else { Pass the smart pointer either by value or reference }
1 The passed object lives longer than it can be used by the receiver.
How
unique_ptr | shared_ptr / weak_ptr | |
---|---|---|
By value | To move the ownership | To share the ownership |
By reference | To modify the smart pointer (e.g. reset) | |
By const ref. | Don’t, better use a raw pointer / ref. | To share the ownership 2 |
2 Faster than by value, but you have to guarantee the lifetime while passing.