2

Possible Duplicate:
What does “Class* &cls” mean in C++'s function definition?

i came across this code:

template <class T,class U> void inline TIntDataSwap2(U data,T i)
{
    unsigned char*& data2=(unsigned char*&)data;
    data2[0]=(unsigned char)(((unsigned int)i>> 8)&0xff);
    data2[1]=(unsigned char)(((unsigned int)i>> 0)&0xff);
};

what is the meaning of the "&" behind "unsigned char *"?

can this only be used in templates? i have never seen it before and "& behind a variable" is hard to google up, please help me...

Community
  • 1
  • 1
user537836
  • 21
  • 2

3 Answers3

1

Reference operator - MSDN source.

Matthew Iselin
  • 10,400
  • 4
  • 51
  • 62
1

The & is not "behind a variable" but part of the type.

You are probably already aware of what a reference is in C++. In this case, unsigned char *& is just a reference to a pointer to unsigned char.

This is completely independent of templates, and can be used inside or outside a template definition,

icecrime
  • 74,451
  • 13
  • 99
  • 111
  • i dont get it? i only know "&" in front of the variable to get the pointer to it. what is the meaning of an "& behind a type specifier" – user537836 Jan 08 '11 at 10:06
  • 1
    @user537836 it is a [reference](http://en.wikipedia.org/wiki/Reference_(C%2B%2B)), and it's an essential concept in C++ (the Wikipedia article will give you some insight, though I'd recommend you get a [good C++ book](http://stackoverflow.com/questions/388242)). – icecrime Jan 08 '11 at 10:08
  • ok i understand now... its like this: void MultiplyByFive(int& number){number *= 5;} >> call by MultiplyByFive(i) <--EQUALS--> void MultiplyByFive(int * number){*number *= 5;} >> call by MultiplyByFive(&i) – user537836 Jan 08 '11 at 10:53
  • @user537836 you get the idea :) Also note that while `number` could be null in the second version, the reference from the first version cannot (which makes it safer) – icecrime Jan 08 '11 at 11:14
1

unsigned char*& is a reference to a pointer to a unsigned char. Always read the pointer/reference combination from right to left. This is in no way restricted to use within templates.

Normally when you pass an argument to a function, it is passed by value in C++ (even huge objects). A copy is made, which is what is passed to the function. This both consumes additional memory and prevents the function from modifying the argument you pass to it (since it only gets a copy). Using a reference, we don't make a copy so it is more memory efficient. It also allows the function to modify the argument if needed. If you only want the performance gain and don't want the function to modify the argument, you can declare the parameter a const reference.

moinudin
  • 134,091
  • 45
  • 190
  • 216
  • thanks, i have never used references before. i understand that you read it from right to left because its like this if you put brackets around it: ((unsigned char *) & ) – user537836 Jan 08 '11 at 11:06