2

The point of passing by reference, I thought, was to pass in the actual variable either to save time or to modify the variable. Thus -- and this is going to make me sound stupid -- I used to think that passing a constant reference somehow temporarily changed the passed-in variable to a constant (if it wasn't already) and then changed it back to a non-constant (unless it was constant to begin with) when the function was done executing. I just learned today when I was reading C++ Primer that passing in a constant reference creates a temporary constant variable. That is,

foo(const type& obj) 

is the same as

foo(const type obj)

because they both create a constant object obj and set it equal to whatever is passed in.

So what's the point of passing by constant reference??? What's the point of references anyways? They're the same thing as pointers, except that they need to be initialized and are thus less useful.

user3178285
  • 151
  • 2
  • 7
  • 3
    Not sure what you (or the book) means by "creating a temporary constant variable", but in any case, a reference is a small object, whereas an actual copy is as large as the original. Constant references are typically used to save space (and time for making copies). – jogojapan Jan 12 '14 at 06:28
  • All a reference does is refer to an existing variable, not create a new one (of that type at least; it'll probably make a pointer under the hood). A const reference does the same with a promise not to modify it. If you pass in a temporary, something has to be created to refer to. – chris Jan 12 '14 at 06:31
  • The easiest way to answer your question is to look at the assembly. – derpface Jan 12 '14 at 08:36

3 Answers3

1

when you pass constant reference no temporary copy is created.....while if you pass constant argument new copy is created....

you can check this by printing the addresses of variable in caller function and callee function.

HadeS
  • 2,020
  • 19
  • 36
1

The right way of doing it is using a constant reference:

foo(const type& obj)

because that way the object is not copied, and that is more efficient especially if the object is big or the function is called multiple times.

Uri Y
  • 840
  • 5
  • 13
0

No. A constant variable creates a temporary variable but a constant reference may not.

cqwrteur
  • 89
  • 8