Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass pointers to objects by constant reference in C++

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.

like image 673
Adri MB Avatar asked Nov 30 '22 13:11

Adri MB


1 Answers

Read the declarations from right to left, using "reference to" for & and "pointer to" for *.

  1. const Tablero *&tablero => tablero is a reference to a pointer to a const Tablero
  2. Tablero* const& tablero => tablero is a reference to a const pointer to a Tablero

I 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.

like image 111
Jerry Coffin Avatar answered Dec 10 '22 03:12

Jerry Coffin