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?
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.
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.
void foobar(TYPE const&); // Pass by const reference
If TYPE is a pointer to a type ABC, then
void foobar(ABC* const&)
is different to
void foobar(const ABC* &)
I believe that is all the author is getting at.
EDIT
This also applies if the typedef is a pointer
typedef SomeStruct* pSomeStruct;
void foobar(pSomeStruct* const &); // const reference to a pointer
// to a pointer to SomeStruct
void foobar(const pSomeStruct* &); // reference to a pointer
// to a const pointer to const SomeStruct
精彩评论