C++ int & 是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4629317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:59:32  来源:igfitidea点击:

What does int & mean

c++pointerstypes

提问by Alfred Zhong

A C++ question,

一个 C++ 问题,

I know

我知道

int* foo(void)

foo will return a pointer to int type

foo 将返回一个指向 int 类型的指针

how about

怎么样

int &foo(void)

what does it return?

它返回什么?

Thank a lot!

非常感谢!

回答by Cameron Skinner

It returns a referenceto an int. References are similar to pointers but with some important distinctions. I'd recommend you read up on the differences between pointers, references, objects and primitive data types.

它返回对 int的引用。引用类似于指针,但有一些重要的区别。我建议您阅读指针、引用、对象和原始数据类型之间的差异。

"Effective C++" and "More Effective C++" (both by Scott Meyers) have some good descriptions of the differences and when to use pointers vs references.

“Effective C++”和“More Effective C++”(均由 Scott Meyers 撰写)对差异以及何时使用指针与引用进行了很好的描述。

EDIT: There are a number of answers saying things along the lines of "references are just syntactic sugar for easier handling of pointers". They most certainly are not.

编辑:有很多答案都说“引用只是为了更容易处理指针的语法糖”。他们肯定不是

Consider the following code:

考虑以下代码:

int a = 3;
int b = 4;
int* pointerToA = &a;
int* pointerToB = &b;
int* p = pointerToA;
p = pointerToB;
printf("%d %d %d\n", a, b, *p); // Prints 3 4 4
int& referenceToA = a;
int& referenceToB = b;
int& r = referenceToA;
r = referenceToB;
printf("%d %d %d\n", a, b, r); // Prints 4 4 4

The line p = pointerToBchanges the value of p, i.e. it now points to a different piece of memory.

该行p = pointerToB更改了 的值p,即它现在指向不同的内存。

r = referenceToBdoes something completely different: it assigns the value of bto where the value of aused to be. It does notchange rat all. ris still a reference to the same piece of memory.

r = referenceToB做一些完全不同的事情:它将 的值分配b给曾经的值a。它根本不会改变rr仍然是对同一块内存的引用。

The difference is subtle but very important.

区别很微妙,但非常重要。

If you still think that references are just syntactic sugar for pointer handling then pleaseread Scott Meyers' books. He can explain the difference much better than I can.

如果您仍然认为引用只是指针处理的语法糖,那么阅读 Scott Meyers 的书。他比我能更好地解释差异。

回答by Alfred Zhong

Be careful here... you're walking the C/C++ line. There's a quite clear distinction but it doesn't always appear that way:

在这里要小心……你正在走 C/C++ 路线。有一个非常明显的区别,但并不总是这样:

C++: this often means a reference. For example, consider:

C++:这通常意味着引用。例如,考虑:

void func(int &x)
{
   x = 4;
}

void callfunc()
{
    int x = 7;
    func(x);
}

As such, C++can pass by value or pass by reference.

因此,C++可以按值传递按引用传递

Chowever has no such pass by reference functionality. & means "addressof" and is a way to formulate a pointer from a variable. However, consider this:

然而,C没有这样的按引用传递功能。& 的意思是“addressof”,是一种从变量中构造指针的方法。但是,请考虑:

void func(int* x)
{
   *x = 4;
}

void callfunc()
{
    int x = 7;
    func(&x);
}

Deceptively similar, yet fundamentally different. What you are doing in Cis passing a copyof the pointer. Now these things still point to the same area of memory, so the effect is like a pass by reference in terms of the pointed-to memory, but it is not a reference being passed in. It is a reference to a point in memory.

看似相似,却有着本质的不同。您在C中所做的是传递指针的副本。现在这些东西仍然指向同一个内存区域,所以效果就像是指向内存的引用传递,但不是传入的引用。它是对内存中某个点的引用。

Try this (Compile as C):

试试这个(编译为 C):

#include <stdio.h>

void addptr(int* x)
{
    printf("Add-ptr scope 1:\n");
    printf("Addr: %p\n", x);
    printf("Pointed-to-memory: %d\n", *x);
    *x = *x + 7;
    x++;
    printf("Add-ptr scope 2:\n");
    printf("Addr: %p\n", x);
    printf("Pointed-to-memory: %d\n", *x);
}

int main(int argc, char** argv)
{
    int a = 7;
    int *y = &a;
    printf("Main-Scope 2:\n");
    printf("Addr: %p\n", y);
    printf("Pointed-to-memory: %d\n", *y);
    addptr(y);
    printf("Main-Scope 2:\n");
    printf("Addr: %p\n", y);
    printf("Pointed-to-memory: %d\n", *y);
    return 0;

}

If C had pass by reference, the incoming pointer address, when changed by addptrshould be reflected in main, but it isn't. Pointers are still values.

如果 C 有通过引用传递,传入的指针地址,当被改变时addptr应该反映在 中main,但它不是。指针仍然是值。

So, Cdoes nothave any pass by reference mechanism. In C++, this exists, and that is what & means in function arguments etc.

所以,Ç没有具有参照机制的任何通行证。在 C++ 中,这是存在的,这就是 & 在函数参数等中的含义。

Edit: You might be wondering why I can't do this demonstration in C++ easily. It's because I can't change the address of the reference. At all. From this quite good guide to references:

编辑:您可能想知道为什么我不能轻松地用 C++ 进行这个演示。那是因为我无法更改引用的地址。在所有。从他非常好的参考指南中

How can you reseat a reference to make it refer to a different object?

No way.

You can't separate the reference from the referent.

Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).

In that sense, a reference is similar to a const pointer such as int* const p (as opposed to a pointer to const such as int const* p). But please don't confuse references with pointers; they're very different from the programmer's standpoint.

如何重新设置引用以使其引用不同的对象?

没门。

您无法将引用与所指对象分开。

与指针不同,一旦引用绑定到一个对象,它就不能“重新定位”到另一个对象。引用本身不是一个对象(它没有身份;获取引用的地址会给你指涉对象的地址;记住:引用是它的指涉对象)。

从这个意义上说,引用类似于诸如 int* const p 之类的 const 指针(而不是指向诸如 int const* p 之类的 const 指针)。但是请不要将引用与指针混淆;从程序员的角度来看,它们是非常不同的。

By request, on returning references:

根据要求,在返回参考文献时:

#include <iostream>

using namespace std;

int& function(int f)
{
   f=f+3;
   return f;
}

int main(int argc, char** argv)
{
    int x = 7;
    int y;
    y = function(x);
    cout << "Input: " << x << endl;
    cout << "Output:" << y << endl;
    return 0;
}

Any good compiler ought to give you this warning message in some form:

任何好的编译器都应该以某种形式给你这个警告信息:

exp.cpp:7:11: warning: reference to stack memory associated with local variable 'f' returned

exp.cpp:7:11: 警告:对与局部变量“f”关联的堆栈内存的引用返回

What does this mean? Well, we know function arguments are pushed onto the stack (note: not actually on x64, they go into registers then the stack, but they are on the stack literally on x86) and what this warning is saying is that creating a reference to such an object is not a good idea, because it's not guaranteed to be left in place. The fact it is is just luck.

这是什么意思?好吧,我们知道函数参数被压入堆栈(注意:实际上不是在 x64 上,它们进入寄存器然后进入堆栈,但它们在 x86 上实际上是在堆栈上)并且这个警告说的是创建对这样的引用一个对象不是一个好主意,因为它不能保证留在原地。事实证明这只是运气。

So what gives? Try this modified version:

那么什么给呢?试试这个修改后的版本:

#include <iostream>

using namespace std;

int& function(int& f)
{
    f=f+3;
    return f;
}

int main(int argc, char** argv)
{
    int x = 7;
    int y;
    y = function(x);
    cout << "Input: " << x << endl;
    cout << "Output:" << y << endl;
    return 0;
}

Run this, and you'll see both values get updated. What? Well they both refer to the same thing and that thing is being edited.

运行这个,你会看到两个值都更新了。什么?好吧,他们都指的是同一个东西,那个东西正在被编辑。

回答by Martin York

From Alfred's comments

来自阿尔弗雷德的评论

This is what the document says, Texas instrument's TMS320C28x C/C++ compiler intrinsics, page 122, int&__byte(int, unsigned int), I guess it is different from PC – Alfred Zhong

这就是文档所说的,德州仪器的 TMS320C28x C/C++ 编译器内在函数,第 122 页,int&__byte(int, unsigned int),我猜它与 PC 不同 – Alfred Zhong

From the manual:

从手册:

int &__byte(int *array, unsigned int byte_index);

MOVB array[byte_index].LSB, src

The lowest adressable unit in C28x is 16 bits. Therefore, normally you cannot access 8-bit MOVB dst, array[byte_index]. LSB entities off a memory location. This intrinsic helps access an 8-bit quantity off a memory location, and can be invoked as follows:

__byte(array,5) = 10;
b = __byte(array,20);

int &__byte(int *array, unsigned int byte_index);

MOVB 数组[byte_index].LSB, src

C28x 中的最低可寻址单元是 16 位。因此,通常您无法访问 8 位 MOVB dst, array[byte_index]。LSB 实体关闭内存位置。这个内在函数有助于访问内存位置的 8 位数量,可以按如下方式调用:

__字节(数组,5)= 10;
b = __byte(array,20);

This just means that the function returns a reference to an integer that acts like an 8 bit quantity. Because the value is a reference modifying will modify the object at the destination (just like the MOVB) instruction, while assigning to b will copy (just like MOVB) to the destination.

这只是意味着该函数返回对整数的引用,该整数的作用类似于 8 位数量。因为值是引用,修改将修改目标处的对象(就像 MOVB)指令,而分配给 b 将复制(就像 MOVB)到目标。

回答by trojanfoe

It returns a reference to an int variable.

它返回对 int 变量的引用。

回答by Puppy

This question isn't C/C++ at all, as C does not have references, only pointers. An int& is a reference to an int. Also, you don't need void, it can just be int& foo();

这个问题根本不是 C/C++,因为 C 没有引用,只有指针。int& 是对 int 的引用。此外,你不需要void,它可以只是int& foo();

回答by Stephane Rolland

just playing with variables to show you the meaning

只是玩弄变量来向你展示意义

int i = 5;
int * pI = &i;
int & referenceToI = * pI;
referenceToI = 4; // now i == 4

EDIT: References are just a syntactic sugar for easier pointers handling. at the assembly level, the code generated by the compiler returns to a you an address-pointer

编辑:引用只是为了更容易处理指针的语法糖。在汇编级别,编译器生成的代码返回给你一个地址指针