有没有“指针引用"的意义? [英] Is there any point of "reference of pointer"?

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

问题描述

我无法理解指针类型的引用是如何工作的.

I can't understand how reference of pointer type works.

  1. 是否有性能差异?

  1. Is there any performance difference?

编译后是否有汇编级别差异?

Is there any assembly level difference if they compiled?

有没有指向指针类型的引用?

Is there any point to reference of pointer type?

vector<Figure*> vFigureList;

//auto&
for(auto& pFigure : vFigureList)
{
    pFigure->draw();
    delete pFigure;
}

//auto
for(auto pFigure : vFigureList)
{
    pFigure->draw();
    delete pFigure;
}

//Figure*
for(Figure* pFigure : vFigureList)
{
    pFigure->draw();
    delete pFigure;
}

//Figure*&
for(Figure*& pFigure : vFigureList)
{
    pFigure->draw();
    delete pFigure;
}

推荐答案

一旦编译,引用就像指针一样,它们提供了一个间接级别.但是它们在 C++ 中有不同的用途:

Once compiled, references are just like pointers, they provide a level of indirection. However they have different use in C++:

  • 它们必须在定义时初始化,因此更安全,就像 const 指针一样.
  • 无需使用 & 运算符的地址来声明它们指向的位置.
  • 无需使用*.
  • They must be initialized upon definition, hence safer, like a const pointer.
  • No need to use the address of & operator to declare where they point to.
  • No need to deference using *.

是否有性能差异?

是的,引用会导致一定程度的指针取消引用,就像普通指针一样.

Yes, references incur a level of pointer dereference, just like a normal pointer.

如果编译,是否有汇编级别的差异?

Is there any assembly level difference if they compiled?

与普通变量相比,是的,额外的间接级别.与指针相比,不,引用和指针在编译后是相同的.

Compared to a plain variable, yes, an extra level of indirection. Compared to a pointer, no, references and pointers are the same once compiled.

有没有指向指针类型的引用?

Is there any point to reference of pointer type?

是的,如果您需要一个指向指针的指针,但又想要引用的安全性和便利性.

Yes, if you needed a pointer to a pointer, but wanted the safety and convenience of a reference.

这是编译器资源管理器上的一个例子(如果链接过期,下面是相同的来源):https://godbolt.org/z/h3WzdPWa1

Here's an example on Compiler Explorer (same source below in case link expires): https://godbolt.org/z/h3WzdPWa1

在没有优化的情况下编译时(不推荐,仅用于说明此编译器资源管理器示例):

When compiled with no optimization (not recommended, just for illustration with this Compiler Explorer example):

  • 直接访问使用三个汇编指令
  • 一级间接(指针和引用)使用五个指令
  • 两级间接(对指针的引用和对指针的指针)使用七条指令

这有助于说明引用实际上是引擎盖下的指针,具有相同的性能影响.

This helps illustrate that references are really pointers under the hood, with the same performance implications.

int num();
int* num_ptr();

int main() {
    int i = num();
    
    int& r = i;
    int* p = num_ptr();

    int*& pr = p;
    int** pp = &p;

    // Direct access
    i += 3;

    // One level of indirection
    r += 5;   
    *p += 7;

    // Two levels of indirection
    *pr += 11;
    **pp += 13;

    return 0;
}

这篇关于有没有“指针引用"的意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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