Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you pass a smart pointer as a function argument in C++?

I am very new to C++ smart pointers and I am having a hard time understanding this advice around using them for function arguments.

"C++ Coding Standards: 101 Rules, Guidelines, and Best Practices " says that these are the reasons to pass in smart pointer.

Prefer passing by (smart) pointer

  • if the argument is optional (so callers can pass null as a “not available” or “don’t care” value)
  • or if the function stores a copy of the pointer
  • or otherwise manipulates ownership of the argument.

Can somebody please give me examples of each one of them and why not using a smart pointer would be a bad idea in the cases?

like image 364
unj2 Avatar asked Dec 09 '22 20:12

unj2


2 Answers

Prefer passing by (smart) pointer [when ...]

I think you are misreading the coding standard. You read this as "these are the reasons to use a smart pointer". What the author intended is "these are the reasons to use some kind of pointer, which might optionally be a smart pointer."

like image 59
Robᵩ Avatar answered Jan 18 '23 23:01

Robᵩ


Prefer passing by (smart) pointer

Note how "smart" is in parenthesis?

What the person is talking about here is passing by pointer vs. reference. Smart is there in parenthesis because you'd follow similar rules when working in a team that prefers smart pointers.

like image 36
Edward Strange Avatar answered Jan 19 '23 00:01

Edward Strange