参考指针 [英] Pointer to reference

查看:54
本文介绍了参考指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读,并且看到了以下代码:

I was reading, and I saw the following code:

template <>
inline bool is_empty(const char* const& x)
{
    return x==0 || *x==0;
}

const char * const&是什么?x 是什么意思?

我尝试了以下代码来理解它:

I tried the following code to understand it:

void f(const char* const& x) 
{
    // whatever
}

void main()
{
    char a = 'z';
    char &j = a;
    f(a);//error
    f(*a);//error
    f(&a);//fine
    f(j);//error
    f(&j);//fine     
    f('z');//error
}

它仅适用于 f(& a) f(& j).

const char * const&是什么?x 到底是什么意思?

推荐答案

指针引用正是它所说的,是对指针的引用.

A pointer reference is exactly what it says, a reference to a pointer.

考虑一下我们对引用的了解.C ++中的引用是一个变量,它引用其他地方的现有变量:

Consider what we know about references. A reference in C++ is a variable that refers to an existing variable elsewhere:

int x = 1;
int &y = x;    // <-- y refers to x. Any changes to y will update x as well, and vice versa.

还要考虑我们对指针的了解.指针指向内存中的另一个对象:

Also consider what we know about pointers. A pointer points to another object in memory:

int *m = new int(5);   // Pointer to an allocated integer in memory.
int *n = m;            // Pointer to the same memory.

因此,在您的情况下,您实际拥有的是对指针的引用!

So in your case what you actually have is a reference to a pointer!

int *m = new int(5);   // Pointer to an allocated integer in memory.
int *ptr = m;          // Pointer to m.
int *&ptrRef = ptr;    // Reference to ptr.

在上面的示例中,更改ptrRef将更新指针,但不会更新该值.

In the example above, changing ptrRef would update the pointer, but not the value.

这里有一个完整的例子:

Here's a bit more of a complete example:

int *myPtr = new int(5);   // myPtr points to an integer.

...

void ChangePointer(int *&ptr)
{
    delete ptr;
    ptr = new int(6);
}

...

std::cout << *myPtr << std::endl;  // <-- Output "5"
ChangePointer(myPtr);
std::cout << *myPtr << std::endl;  // <-- Output "6"

在上面的示例中,我们通过引用将 myPtr 传递给 ChangePointer ,以便可以通过函数对其进行修改.如果我们不通过引用传递,则函数内部所做的任何更改都将丢失.

In the example above, we pass myPtr to the ChangePointer by reference so that it can be modified by the function. If we did not pass by reference, any changes made inside the function would be lost.

在您的情况下,您正在传递对const指针的引用.这大约等于:

In your case, you're passing a reference to a const pointer. This is approximately equivalent to:

DoStuff(const Object &myObject);

在您的情况下,您传递的是指针,而不是对象.

In your case, you're passing a pointer, rather than an object though.

虽然通过引用传递const指针似乎有点多余.不能更改指针(它是const),并且按引用传递指针没有好处(对于像指针和整数之类的小对象,按引用传递没有比按值传递更有效).我不想猜测为什么要在您的情况下完成.

It seems a bit redundant to pass a const pointer by reference though. The pointer cannot be changed (it is const), and there is no benefit to passing pointers by reference (pass by reference is no more efficient than pass by value for small objects like pointers and integers). I wouldn't want to guess as to why it was done in your case.

这篇关于参考指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆