Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could somebody elaborate 'use a const pointer when the non-optional form would have used a reference'? #639

Open
junsoopark opened this issue Jun 16, 2021 · 2 comments
Labels
lang:cpp The C++ language question

Comments

@junsoopark
Copy link

junsoopark commented Jun 16, 2021

in cppguide.html,
Could somebody please elaborate 'use a const pointer when the non-optional form would have used a reference'? It will be also helpful if some examples can be added.

My understanding is as follows,

  • Non-optional input parameters - values or const references
  • Non-optional output and input/output parameters - references
  • Optional input parameters(by value) - absl::optional
  • the non-optional form would have used a reference(<= This means Optional input parameters by references?) - a const pointer
  • Optional outputs and optional input/output parameters - non-const pointers

Thanks in advance.

Parameters are either inputs to the function, outputs from the function, or both. Non-optional input parameters should usually be values or const references, while non-optional output and input/output parameters should usually be references (which cannot be null). Generally, use absl::optional to represent optional by-value inputs, and use a const pointer when the non-optional form would have used a reference. Use non-const pointers to represent optional outputs and optional input/output parameters.

@gou4shi1
Copy link

gou4shi1 commented May 10, 2022

I can't understand this too, does it mean if you can't use const &, then use const * as non-optional input?

@tituswinters
Copy link
Contributor

It's trying to clarify the comparisons: T* is to T& what optional<T> is to T. If you would be passing by value, but want optionality, you pass optional<T>. If you would be passing by reference but want optionality, pass T*.

@vapier vapier added question lang:cpp The C++ language labels Jul 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lang:cpp The C++ language question
Projects
None yet
Development

No branches or pull requests

4 participants