Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The fact that references can be <em>implemented</em> in terms of pointers under the hood is irrelevant. Many programming concepts can be implemented in terms of other things. You may as well ask why we have <code>while</code> loops when <code>while</code> can be implemented in terms of <code>goto</code> or <code>jmp</code>. The point of different language concepts is to make things <em>easier</em> for the programmer, and references are a language-concept designed for the convenience of the programmer. </p> <p>You probably are misunderstanding the <em>purpose</em> of references. References give you the positive side of pointers (cheap to pass around), but since they have the same semantics as regular values, they remove a lot of the dangers that come with using pointers: (pointer arithmetic, dangling pointers, etc.) More importantly, a reference is a totally different <em>type</em> than a pointer in the C++ type-system, and it would be madness to allow the two to be interchangeable (that would defeat the purpose of references.)</p> <p>Reference syntax is designed <em>on purpose</em> to mirror the syntax of regular value semantics - while at the same time providing you with the ability to cheaply pass around memory addresses instead of copying entire values.</p> <p>Now, turning to your example:</p> <pre><code>FooRef(*p); // why do I have to dereference the pointer? </code></pre> <p>You have to dereference the pointer here because <code>FooRef</code> takes a <em>reference</em> to an <code>int</code>, not a reference to an <code>int*</code>. Note that you can also have a <em>reference to a pointer</em>:</p> <pre><code>void FooPointerRef(const int*&amp;); </code></pre> <p>A function that takes a reference to a pointer enables you to modify the memory address of the pointer from within the function. In your example, you have to explicitly dereference the pointer to mirror value semantics. Otherwise, someone looking at the function call <code>FooRef(p)</code> is going to think that <code>FooRef</code> either takes a pointer-by-value or a pointer-by-reference - but NOT a (non-pointer) value or a reference.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload