“&”是什么? C++ 中的变量后面模板?
我遇到了这段代码:
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);
};
“&”的含义是什么?在“unsigned char *”后面?
这只能在模板中使用吗?我以前从未见过它,并且“变量后面的&”很难用谷歌搜索,请帮助我......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
引用运算符 - MSDN 源。
Reference operator - MSDN source.
&
不是“变量后面”,而是类型的一部分。您可能已经知道 C++ 中的引用是什么。在这种情况下,
unsigned char *&
只是对unsigned char
指针的引用。这完全独立于模板,可以在模板定义内部或外部使用,
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 tounsigned char
.This is completely independent of templates, and can be used inside or outside a template definition,
unsigned char*&
是对指向unsigned char
的指针的引用。始终从右向左读取指针/参考组合。这绝不限于在模板中使用。通常,当您将参数传递给函数时,在 C++ 中它是按值传递的(甚至是巨大的对象)。制作了一个副本,该副本被传递给函数。这既消耗额外的内存,又阻止函数修改传递给它的参数(因为它只获取一个副本)。使用引用,我们不进行复制,因此内存效率更高。它还允许函数根据需要修改参数。如果您只想提高性能并且不希望函数修改参数,则可以将参数声明为
const
引用。unsigned char*&
is a reference to a pointer to aunsigned 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.