在实现中,引用与指针不同的是什么? [英] How is a reference different from a pointer in implementation?

查看:135
本文介绍了在实现中,引用与指针不同的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++中的指针变量和引用变量之间的差异

我正在阅读Stanley Lippman的C ++对象模型内部一书。让我困惑的是对象的引用和对象的指针之间的区别。我知道一个引用必须在声明时初始化,而一个指针可以留给以后初始化。但我想知道它们之间的物理实现差异。

I am reading about the book "Inside the C++ Object Model" by Stanley Lippman. What puzzles me is the difference between a "reference" of an object and a "pointer" to an object. I know that a reference must be initialized when declared, while a pointer could be left for later initialization. But I want to know the physical implementation difference between them.

为什么应该有引用机制;是不是它重叠的指针的功能?在什么情况下我们应该使用指针以外的引用?非常感谢。

Why should there be the "reference" mechanism; isn't it overlapping the function of a pointer? Under what circumstance should we use reference other than pointer? Many thanks.

推荐答案

大多数引用是使用指针变量实现的,即引用通常占用一个内存字。 然而,纯粹在本地使用的引用可以 - 并且常常被优化器消除。例如:

Most references are implemented using a pointer variable i.e. a reference usually takes up one word of memory. However, a reference that is used purely locally can - and often is - eliminated by the optimizer. For example:

  struct S { int a, int b[100]; };  
  void do_something(const vector<S>& v)
  {
    for (int i=0; i<v.size(); ++i) {
        int*& p = v[i].b;
          for (int j=0; j<100; ++j) cout <<p[j];
  }

在这种情况下,p不需要存储在内存中在寄存器中,也许它会消失在指令中)。

In this case, p needs not be stored in memory (maybe it just exists in a register, maybe it disappears into the instructions).

这篇关于在实现中,引用与指针不同的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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