简体   繁体   English

int & 是什么意思

[英]What does int & mean

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!非常感谢!

It returns a reference to an int.它返回对 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.我建议您阅读指针、引用、对象和原始数据类型之间的区别。

"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 = pointerToB changes the value of p , ie it now points to a different piece of memory.p = pointerToB改变了p的值,即它现在指向另一块内存。

r = referenceToB does something completely different: it assigns the value of b to where the value of a used to be. r = referenceToB做了一些完全不同的事情:它将b的值分配给a的值。 It does not change r at all.它根本不会改变r r is still a reference to the same piece of memory. r仍然是对同一块内存的引用。

The difference is subtle but very important.差异是微妙的,但非常重要。

If you still think that references are just syntactic sugar for pointer handling then please read Scott Meyers' books.如果您仍然认为引用只是指针处理的语法糖,那么阅读 Scott Meyers 的书籍。 He can explain the difference much better than I can.他可以比我更好地解释差异。

Be careful here... you're walking the C/C++ line.在这里要小心……您正在走 C/C++ 路线。 There's a quite clear distinction but it doesn't always appear that way:有一个非常明显的区别,但并不总是这样:

C++ : this often means a reference. C++ :这通常意味着引用。 For example, consider:例如,考虑:

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++可以按值传递或按引用传递。

C however has no such pass by reference functionality.然而, C没有这样的引用传递功能。 & means "addressof" and is a way to formulate a pointer from a variable. & 表示“addressof”,是一种从变量制定指针的方法。 However, consider this:但是,考虑一下:

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

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

Deceptively similar, yet fundamentally different.看似相似,却有着本质的不同。 What you are doing in C is passing a copy of the pointer.您在C中所做的是传递指针的副本 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.现在这些东西仍然指向同一个内存区域,所以就所指向的内存而言,效果就像是通过引用传递,但传入的不是引用。它是对内存中某个点的引用。

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 addptr should be reflected in main , but it isn't.如果 C 通过引用传递,则传入指针地址在被addptr更改时应该反映在main中,但事实并非如此。 Pointers are still values.指针仍然是值。

So, C does not have any pass by reference mechanism.因此, C没有任何引用传递机制。 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.编辑:您可能想知道为什么我不能轻松地在 C++ 中进行此演示。 It's because I can't change the address of the reference.这是因为我无法更改引用的地址。 At all.完全没有。 From t his quite good guide to references :他相当好的参考指南

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).从这个意义上说,引用类似于 const 指针,例如 int* const p(与指向 const 的指针,例如 int const* p 不同)。 But please don't confuse references with pointers;但请不要将引用与指针混淆; they're very different from the programmer's standpoint.从程序员的角度来看,它们非常不同。

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.好吧,我们知道函数参数被压入堆栈(注意:实际上不是在 x64 上,它们进入寄存器然后进入堆栈,但它们在 x86 上实际上在堆栈上),这个警告的意思是创建对此类的引用一个对象不是一个好主意,因为它不能保证留在原地。 The fact it is is just luck.事实上,这只是运气。

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.好吧,他们都指的是同一件事,而那件事正在被编辑。

它返回对 int 变量的引用。

This question isn't C/C++ at all, as C does not have references, only pointers.这个问题根本不是 C/C++,因为 C 没有引用,只有指针。 An int& is a reference to an int. int& 是对 int 的引用。 Also, you don't need void , it can just be int& foo();此外,您不需要void ,它可以只是int& foo();

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); int &__byte(int *array, unsigned int byte_index);

MOVB array[byte_index].LSB, src MOVB 数组[byte_index].LSB, src

The lowest adressable unit in C28x is 16 bits. C28x 中的最低可寻址单元是 16 位。 Therefore, normally you cannot access 8-bit MOVB dst, array[byte_index].因此,通常不能访问 8 位 MOVB dst, array[byte_index]。 LSB entities off a memory location. LSB 实体离开内存位置。 This intrinsic helps access an 8-bit quantity off a memory location, and can be invoked as follows:此内在函数有助于访问内存位置的 8 位数量,并且可以按如下方式调用:

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

This just means that the function returns a reference to an integer that acts like an 8 bit quantity.这只是意味着该函数返回对一个整数的引用,该整数的作用类似于 8 位量。 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.因为值是一个引用,修改将修改目标处的对象(就像 MOVB)指令,而分配给 b 将复制(就像 MOVB)到目标。

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在汇编级别,编译器生成的代码返回给你一个地址指针

https://isocpp.org/wiki/faq/references https://isocpp.org/wiki/faq/references

This page says it succinctly!这一页说的很简洁! A reference is an alias.引用是别名。 It IS the object, just by another name.它是对象,只是另一个名称。 The previous name is still valid.以前的名称仍然有效。 The reference is not a stand-alone object.引用不是独立对象。 It IS the object by a different name.它是不同名称的对象。 You cannot operate on the reference because it is not a thing unto itself.您不能对引用进行操作,因为它本身不是事物。 It is just an alias of the original object.它只是原始对象的别名。

It is that simple.就是这么简单。 Now you can think of it easily rather than the round and round in the above posts.现在您可以轻松地想到它,而不是上面的帖子中的一轮又一轮。

int& is a reference. int& 是一个参考。 To be more precise, a reference variable is simply an alternative name of an existing variable.更准确地说,引用变量只是现有变量的替代名称。

Example: Consider below code示例:考虑下面的代码

main(){
    int x = 4;
    int& ref_of_x = x;
    // Now, modifying x modifies ref_of_x too and vice-versa
    x = 5;
    cout<<ref_of_x; //This prints 5
    
    ref_of_x = 15;
    cout<<x;  // This prints 15
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM