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...
Reference operator - MSDN source.
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,
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.
精彩评论