What is the difference between references and pointers in C++

What is the fundamental difference between a reference and a pointer in C++? When is it better to use a reference, and when is a pointer? What are the limitations of the former, and what are the latter?

Author: demonplus, 2010-11-22

2 answers

More differences:

  1. You cannot declare an array of references.
  2. The link doesn't have an address.
  3. There is pointer arithmetic, but no reference arithmetic.
  4. A pointer can have an "invalid" value with which it can be compared before being used.

    If the caller cannot fail to pass the reference, then the pointer can have a special value. nullptr:

    void f(int* num, int& num2)
    {
       if(num != nullptr) // if nullptr ignored algorithm
       {
       }
       // can't check num2 on need to use or not
    }
    

    Http://rextester.com/EQMC52074

    (Standart) A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.

  5. The link does not have a qualifier const

    #include <iostream>
    int main()
    {
        std::cout << "Hello, world!\n";
    
        const int v = 10;
        //int& const r = v; // Ошибка
        const int& r = v;
    
        enum
        {
            is_const = std::is_const<decltype(r)>::value
        };
    
        if(!is_const)
            std::cout << "const int& r is not const\n";
        else
            std::cout << "const int& r is const\n";
    }
    

About fun

Some refer to an excerpt from an interview with Stroustrup:

The obvious implementation of a reference is a (constant) pointer, which is dereferenced every time it is used. In some cases, the compiler may optimize the reference so that no object representing the reference exists at all at runtime.

Others ask only one question in response:

What is the result of dereferencing a pointer?

On the topic of whether you need to know the difference between a pointer and a reference, Joel Spolsky wrote in his article " The Law of Leaky Abstractions ".

 41
Author: rikimaru2013, 2016-07-01 19:20:35

There are two fundamental differences:

  • a reference, unlike a pointer, cannot be uninitialized;
  • the reference cannot be changed after initialization.

Hence we get the pros and cons of using both:

  • links are best used when it is undesirable or not planned to change the link link → object;
  • the pointer is best used when the following points are possible during the link's lifetime:
    • the link is not points to no object;
    • a reference points to different objects during its lifetime.
 35
Author: a_s, 2016-04-26 11:25:30