I'm doing a practical assignment for university and I've run into a problem. I've got a class that declares this method:
bool graficarTablero(const Tablero *&tablero, const string &nombreArchivo);
I want to pass a pointer to an object Tablero by constant reference. If I call that function like, say for example:
ArchivoGrafico *grafico = new ArchivoGrafico;
if(grafico->graficarTablero(tablero, ARCHIVO_GRAFICO)){ ...
...I get compilation errors. Ok, I won't detail the error I get cause I think I already found a solution for it, by replacing the method header for:
bool graficarTablero(Tablero* const& tablero, const string &nombreArchivo);
Now that SEEMS to work (at least it compiles now), but what I'd like to know is the reason why the first declaration doesn't work while the second does. Well, more importantly what I'd really like to know if they actually mean the same thing (pointer to object by constant reference).
Well, thanks for your answer.
EDIT 1: What I'd like to do is to avoid passing by value. Well, I know it's not really an expensive operation, but is there really no way to use the same pointer with the promise that it won't be modified in any way?
Thanks.
EDIT 2: Sorry, I didn't read Jerry Coffin's answer carefully enough. Yes, that's what I was looking for. It's not that I really have to do that, but I may find that little optimization useful some day.
Read the declarations from right to left, using "reference to" for &
and "pointer to" for *
.
const Tablero *&tablero
=> tablero is a reference to a pointer to a const TableroTablero* const& tablero
=> tablero is a reference to a const pointer to a TableroI have a hard time figuring out a situation in which the latter would be useful -- if you're going to pass a const reference, you might about as well just pass a copy of the pointer itself. A const reference is normally used primarily as an alternative to passing by value, but avoiding making a copy of the value, so it's useful primarily when your value is something large (e.g., a large std::vector
or something on that order). In the case of a pointer, you might about as well pass it by value (since copying a pointer is normally quite cheap). Usually if you're passing a pointer by reference, it's so you can modify the pointer -- but in this case the const
prevents that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With