• Advertisement
Sign in to follow this  

C++ function params: pointer-to-const vs. reference-to-const

This topic is 3849 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've got a quick (hopefully) question. :) Are there any semantic differences between the following code segments, and if so what would be the reasons to prefer one over the other?
void Foo(const Bar* bar);
void Foo(const Bar& bar);
Other than personal preference of using "->" or ".", are there any other reasons I should lean to using one or the other of these?

Share this post


Link to post
Share on other sites
Advertisement
If the parameter can refer to a null pointer then you should use a pointer, otherwise use a reference.

Share this post


Link to post
Share on other sites
You can pass an unnamed temporary into a function taking a const reference, but not a pointer. This can be very convenient.

Share this post


Link to post
Share on other sites
I difference is:
const Bar* bar is a pointer to a const Bar
but you can do the following (eg. by mistake)

const Bar A,B;
const Bar* ptrA = &A;
ptrA = &B;

so you could chang what the pointer points to in the function scope. Which of course you can not with a reference.

So execpt for what rip-off said the following will behave the same:

const Bar* const bar
const Bar& bar


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement