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

Started by
2 comments, last by dragongame 16 years, 8 months ago
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?
Advertisement
If the parameter can refer to a null pointer then you should use a pointer, otherwise use a reference.
You can pass an unnamed temporary into a function taking a const reference, but not a pointer. This can be very convenient.
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


“Always programm as if the person who will be maintaining your program is a violent psychopath that knows where you live”

This topic is closed to new replies.

Advertisement