Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pass by const reference syntax

I know the topic of pass by reference vs. pass by pointer is heavily covered... Pretty sure I understood all the nuances until I read this:

http://carlo17.home.xs4all.nl/cpp/const.qualifier.html

which reads (in case the link goes dead)

The prototype for foobar can have any of the following footprints:
void foobar(TYPE);      // Pass by value
void foobar(TYPE&);     // Pass by reference
void foobar(TYPE const&);   // Pass by const reference

Note that I put the const to the right of TYPE because we don't know if TYPE (this is not a template parameter, but rather for instance a literal char*) is a pointer or not!

what does the author mean by "Note that I put the const to the right of TYPE because we don't know if TYPE ... is a pointer or not!"

Everything I've read on this topic has been consistent in saying that:

void foodbar(TYPE const &)

is equivalent too

void foobar(const TYPE &)

If I understand the author correctly, s/he is saying that:

const int *X vs int * const X where pointer, X itself is const vs. what X points to is const?

If so, is this true?

like image 821
Eric Avatar asked Jun 04 '11 05:06

Eric


2 Answers

If TYPE is a #define for something like int*, the placement of const does matter. In that case you will get const int* or int* const depending on the placement of const.

If TYPE is a typedef or a template parameter, the const will affect the whole type either way.

To me this looks more like another argument against macros, rather than a need for some specific style in declarations.

like image 107
Bo Persson Avatar answered Oct 09 '22 03:10

Bo Persson


Looking at the C++ FAQ Lite (as the article suggests), you read pointer declarations from right-to-left. So if TYPE is a pointer, the placement of the * does make a difference. Follow the link for the full story.

like image 20
Gnawme Avatar answered Oct 09 '22 04:10

Gnawme