Pass pointers to objects by constant reference in C++

与世无争的帅哥 提交于 2019-12-21 06:19:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16071305/pass-pointers-to-objects-by-constant-reference-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!