Pass pointers to objects by constant reference in C++ -


i'm doing practical assignment university , i've run problem. i've got class declares method:

bool graficartablero(const tablero *&tablero, const string &nombrearchivo); 

i want pass pointer object tablero constant reference. if call function like, example:

archivografico *grafico = new archivografico; if(grafico->graficartablero(tablero, archivo_grafico)){ ... 

...i compilation errors. ok, won't detail error cause think found solution it, replacing method header for:

bool graficartablero(tablero* const& tablero, const string &nombrearchivo); 

now seems work (at least compiles now), i'd know reason why first declaration doesn't work while second does. well, more importantly i'd know if mean same thing (pointer object constant reference).

well, answer.


edit 1: i'd avoid passing value. well, know it's not expensive operation, there no way use same pointer promise won't modified in way?

thanks.


edit 2: sorry, didn't read jerry coffin's answer enough. yes, that's looking for. it's not have that, may find little optimization useful day.

read declarations right left, using "reference to" & , "pointer to" *.

  1. const tablero *&tablero => tablero reference pointer const tablero
  2. tablero* const& tablero => tablero reference const pointer tablero

i have hard time figuring out situation in latter useful -- if you're going pass const reference, might pass copy of pointer itself. const reference used alternative passing value, avoiding making copy of value, it's useful when value large (e.g., large std::vector or on order). in case of pointer, might pass value (since copying pointer quite cheap). if you're passing pointer reference, it's can modify pointer -- in case const prevents that.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -