简体   繁体   English

对对象的 C++ 引用是否类似于 C 中的双指针?

[英]Is a C++ reference to an object analogous to a double pointer in C?

I am reading "Accelerated C++" by Koenig.我正在阅读 Koenig 的“Accelerated C++”。 In chapter 5, Koenig defines a function which has a reference to a vector parameter.在第 5 章中,Koenig 定义了一个引用向量参数的函数。 In the function body, a new vector is created and assigned to the parameter.在函数体中,创建了一个新向量并将其分配给参数。

Is a reference to an object analogous to a double pointer in C?对对象的引用是否类似于 C 中的双指针?

I am imagining a local variable which is a pointer to a data structure on the heap (a vector in this case).我正在想象一个局部变量,它是一个指向堆上数据结构的指针(在这种情况下是一个向量)。 The address of this variable (a double pointer) is passed to a function and, in the function body, is dereferenced and assigned the address of a new data structure on the heap (in this case, a new vector).这个变量的地址(一个双指针)被传递给一个函数,并在函数体中被取消引用并分配堆上一个新数据结构的地址(在这种情况下,一个新向量)。

I realize references have different properties than pointers and that references are not necessarily implemented as pointers.我意识到引用具有与指针不同的属性,并且引用不一定实现为指针。 However, is the above a reasonable way to think about things?然而,以上是一种合理的思考方式吗?

A pointer is always a separate value, that is in the case of:指针始终是一个单独的值,即在以下情况下:

int x = 1;
int *y = &x;

There are two values here, x and y .这里有两个值, xy These have different addresses such that:它们具有不同的地址,例如:

&x != &y

In the case of references it's just a code alias , not an actual separate thing, so:在引用的情况下,它只是一个代码别名,而不是一个实际的单独的东西,所以:

int x = 1;
int &y = x;

Where now you have two names for exactly the same thing:现在你有两个完全相同的名字:

&x == &y

As x and y are from that point forward effectively interchangeable.因为xy起可以有效地互换。

Remember that pointers must be de-referenced to be used.请记住,必须取消引用指针才能使用。 A reference requires no such special handling.引用不需要这种特殊处理。

Where there's similarity is that a pointer can be used to manipulate a shared value, or a pointer-pointer to manipulate a pointer, but there is a level of indirection that makes it different.相似之处在于指针用于操作共享值,或指针指针可用于操作指针,但有一个间接级别使其不同。

In C where you don't have references you use pointers instead, so you have functions like this:在没有引用的 C 中,你使用指针代替,所以你有这样的函数:

void mutate(int* v);

Where that's a pointer meaning "mutable value", though in C++ it looks like:这是一个表示“可变值”的指针,尽管在 C++ 中它看起来像:

void mutate(int& v);

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

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