2

Possible Duplicate:
C++: When to use References vs. Pointers

I'm pretty new programmer to the C/C++ languages and since I am coming from a background of C#, Java, JavaScript and a little bit of Visual Basic and Python, I am having a hard time to understand some of the things in C++.

I already know how to use reference and pointers and what they really mean, etc. But I don't understand why and where to use them. I know that references sometimes are used like this:

int x = 2;

void Square(int &value)
{
   value = value*value;
}

Square(x);

cout << x << endl;

And the output will be 4.

I thought I don't quite understand why to do it that way and not do like this:

int x = 2;

int Square(int value)
{
   value = value*value;
   return value;
}

x = Square(x);

cout << x << endl;

Anyway, I hope someone may be able to help me understand why and where to use reference and pointers.

Community
  • 1
  • 1
UnTraDe
  • 3,747
  • 10
  • 36
  • 60

7 Answers7

3

You pass references for two main reasons:

  • to change the value of the object referenced inside your function
  • to avoid the cost of copying the object you pass

If you want the second benefit but not the first, you usually pass a const reference to avoid mistakenly changing the object passed.

In C++, pointers and references are much the same with two exceptions:

  • A reference cannot point to 0 (or nullptr)
  • A reference must always point to the same object

If you want to do one of these things, you have to use a pointer.

Additionally, pointers usually point to objects created in the heap by using new, while references usually point to objects created in the stack. This means that the lifetime of objects pointed to by pointers is usually controlled manually. You have to explicitly call delete on objects created by new in order to destroy them, but the lifetime of objects created in the stack is automatically managed by the runtime (hence their name "automatic variables").

I don't know if this is all you needed to know or you are looking for something more specific.

Gorpik
  • 10,940
  • 4
  • 36
  • 56
  • 2
    Worth noting that a very common mistake of beginning C++ programmers is using pointers where they could (and should) use a reference. I.e dont allocate things on the heap with new unless you have to, and dont pass pointers around (use references) unless you have to. – Ricibob Apr 09 '12 at 08:46
  • Ok i will try to keep that in mind. – UnTraDe Apr 09 '12 at 08:58
1

There's no practical difference for an example like that, but instead of passing an integer to Square(), imagine square was a complex algorithm that took 10 gigabytes of data. Wouldn't you be better off using a pointer, so the parameter doesn't get copied?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

The second example will make locally copy your variable x (only visible inside Square function).

If you want make sure that your global x will stay non-changed, do it that way. However, it may be expensive (if your variable is bigger object/struct)... and redundant - check out keyword const.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
0

Passing argument as reference means that you are going to modify its value (if you do some operation on it)and not of a variable that is a copy of it. Since you use &value it changes the contents stored at the address pointed by &value.

And you need to pass &x in place of x in Squre().

So x= Squre(&x);

or

Squre(&x);

is same.

Dynamite
  • 341
  • 2
  • 5
  • 17
0

A reference is just a pseudo name for a variable. Any action applied to a reference actually impacts the variable you refer to

int a = 5;
int &b = a;
b++; // 'a' gets equal to 6

In your example you return the result of multiplication, but what if you need to change value of a variable passed to a function which returns nothing?

This is when references become handy. A pointer behaves in a similar way except that pointer is not a pseudo name for a variable, but its address. You could pass a pointer to a variable to a function, dereference it, and it would impact your variable in exactly the same way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
  • Thanks! I already know what you've said in the example, but i dont really understood why it's usefull. Only for memory managment? – UnTraDe Apr 09 '12 at 08:38
0

Well, for POD structures, you won't see a lot of benefits, because the operation = is easy to understand.

So your x = square(x) pretty much does what it says, with quite good performance.

The advantage of using a pointer/reference arises when you pass objects to your methods. In this case:

Object x;

Object squre( Object x )
{
    x._internalvalue = x._internalvalue * x._internalvalue;
    return x;
}

x = squre(x);

The processes taking place here are totally different: the = sign doesn't automagically applies to objects, so you'll have to implement what's called the rule of three, in which you'll find an assignment operator. The assignment operator, though, is quite expensive, because it has to recreate a new (temporary) object in memory, call the assignment operator, then copy the memory of this object back to your original x.

Also, passing an object as argument of a function will force the processor to copy the entire memory taken by this object on the stack, to have access to it in the function, which is very costly.

So, to answer your question, you start to see the benefits of using references and pointers when you start to manipulate structures and objects, which are WAY bigger than plain old integers.

Programming with references will give you a boost of performances and limit the risks of a stack overflow when you manipulate big objects.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gui13
  • 12,993
  • 17
  • 57
  • 104
  • Ok but what's happening on c# for exmaple? I know you have ref and out or something like this but i don't remember i saw it in use somewhere. Or maybe i saw and just forgot. – UnTraDe Apr 09 '12 at 09:06
0

Reference is used when you want to refer to a variable using another name. They have exactly the same type, value, etc.
Pointer is somewhat different, it is a new type to store the address.

int i;  
Int &ref = i;  
Int *pointer = &i;  

Then ref and *pointer is in fact the same thing, the value of i.
But you have to know that the literal "ref" is just "i" (it can never change after initialized) but "pointer" just temporarily points to i.
So in most times they are the same thing.
Then when do we use reference or pointer?
In my opinion, use which is more convenient.
For example, a reference can not be changed, but a pointer a point to different things.^_^
Ah, I forget the cost of copying, please check the other's answers.

cloudygoose
  • 608
  • 1
  • 6
  • 16