“&”是什么? C++ 中的变量后面模板?

发布于 2024-10-11 10:27:35 字数 629 浏览 3 评论 0原文

可能的重复:
C++ 函数定义中的“Class* &cls”是什么意思?

我遇到了这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柠檬色的秋千 2024-10-18 10:27:35

引用运算符 - MSDN 源

Reference operator - MSDN source.

听风吹 2024-10-18 10:27:35

& 不是“变量后面”,而是类型的一部分。

您可能已经知道 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 to unsigned char.

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

风筝有风,海豚有海 2024-10-18 10:27:35

unsigned char*& 是对指向 unsigned char 的指针的引用。始终从右向左读取指针/参考组合。这绝不限于在模板中使用。

通常,当您将参数传递给函数时,在 C++ 中它是按值传递的(甚至是巨大的对象)。制作了一个副本,该副本被传递给函数。这既消耗额外的内存,又阻止函数修改传递给它的参数(因为它只获取一个副本)。使用引用,我们不进行复制,因此内存效率更高。它还允许函数根据需要修改参数。如果您只想提高性能并且不希望函数修改参数,则可以将参数声明为 const 引用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文