0

In Google c++ code style, they have said there are some instances where using const T* is preferable to const T& for input parameters.

  1. You want to pass in a null pointer
  2. The function saves a pointer or reference to the input.

I don't understand the second one. Could you give me some examples? Thanks.

Marc.2377
  • 7,807
  • 7
  • 51
  • 95
liangsun
  • 37
  • 5
  • Did the style document not go into more detail? – JaMiT Oct 07 '19 at 01:21
  • 3
    Sorry, but the Google Style Guide is infamous for being against idiomatic C++. Probably you shouldn't be following it unless you are forced to. – L. F. Oct 07 '19 at 01:25
  • Hi. In addition to what @L.F. has said, please see: [difference between a pointer and reference parameter?](https://stackoverflow.com/q/620604/3258851), [Pointers vs. References in C++ function arguments](https://stackoverflow.com/q/17900022/3258851), [Pass by reference vs pass by pointer?](https://stackoverflow.com/q/5893873/3258851) and [When to pass by reference and when to pass by pointer in C++?](https://stackoverflow.com/q/3613065/3258851), and duplicated/related questions. – Marc.2377 Oct 07 '19 at 01:32
  • @L.F. Sorry,I have updated the question,Please take another look. – liangsun Oct 07 '19 at 01:44
  • @Marc.2377 I have updated the question. PTAL – liangsun Oct 07 '19 at 01:46
  • @JaMit I have added the detail.PTAL – liangsun Oct 07 '19 at 01:47
  • @liangsun The second point looks like a (subjective) convention. If you use that convention and a function takes a pointer that cannot be null, then you can deduce that a copy of the pointer will be kept. At that point you should check the documentation to see how long the pointer will be kept. There are other ways to achieve the same goal (such as checking the documentation before using the function), so I would still go with the question being primarily opinion-based. – JaMiT Oct 07 '19 at 10:46

1 Answers1

1

there are some instances where using const T* is preferable to const T& for input parameters

2.The function saves a pointer or reference to the input. I don't understand the second one. Could you give me some examples

Example:

int* ptr;
void foo(int& ref)
{
    ptr = &ref; // function saves a pointer or reference to the input
                // therefore using ref input is not preferable
                // according to the guideline
}
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326