What are the differences between pointer and reference in c ++?

7

This question is a specific c ++ version of the question: #

In practice, what are the differences between a pointer and a reference in C ++?

I say in practice because I would not like merely descriptive and sometimes ambiguous answers, such as some in that SOen question . What I look for are practical illustrations of these differences, which in addition to the explanation contain examples of simple, straightforward codes.

    
asked by anonymous 12.01.2016 / 21:04

3 answers

2
  • references themselves (not the referenced type), are always const , so always initialized only once, not pointers.

It can be difficult to imagine an attempt to reset a reference, since after the initial initialization where bind is done with a variable, the following assignments will always treat the reference as an alias for the original variable, and not an attempt to rebind to another variable. But it is possible to replicate this when dealing with references in an indirect way, forcing the rebind situation, eg:

struct S {
    int &x;
};

int main() {
    int a = 0, b = 0;
    S s1{ a }, s2 { b };

    s2 = s1;

    // Clang Error:
    //
    // refs.cpp:9:8: error: object of type 'S' cannot be assigned because its
    //                      copy assignment operator is implicitly deleted
    //     s2 = s1;
    //        ^
    // refs.cpp:2:10: note: copy assignment operator of 'S' is implicitly
    //                      deleted because field 'x' is of reference type
    //                      'int &'
    //     int &x;
    //          ^
    // 1 error generated.
}

s1 and s2 are two simple objects of type S that have a reference member. I build them by having members reference two different variables.

When I try to do a trivial assignment , which is just a simple copy of memory (which in theory would be a means of circumventing the system in order to achieve a rebind of the internal reference, leaving both referencing the same variable, since s1 and s2 would be equal bit-a -bit) the compiler does not allow.

This same type of error would occur if the member were a const int x or int * const x , since it is not possible to reset const variables.

Bonus

C ++ has pointers and references, Java, as many people say, "passes objects by reference". Not really, actually Java has pointers, and it passes everything by value, including pointers, erroneously referenced treatises . / p>     

13.01.2016 / 19:27
0

References make a pointer-like paper, but the address it references is immutable. When you move a reference, you're not doing anything but tinkering with the variable it references, it never changes. They are equivalent, but they must be used according to the cases in which they are requested, performing their fundamental functions. There is also a specific type of referencing that behaves differently, called rvalue reference . It is used when the variable lifetime is small .

What also changes is the way the compiler will handle the variable you have, the syntactic sugar and good practices. This is very general in this way, so let's look at an example. If you have a int f(int&) function, you can enter either a int& or a *(int*) , correct - in these cases, they necessarily complement each other. Because this is the basics, a concept that came from C for C ++. If you look at the most common Windows or Linux APIs, you will notice that changing variables are always passed by pointers, since C there were no references . They have created these references to make the program safer and "handsome" because, after all, pointers are one of the most "unpredictable" things about programming errors.

If you know Assembly, the difference of a pointer is that, (analogously, not literally,) when you call a mnemonic or perform a function, it performs MNM var , and with a reference, MNM [var] . This is equivalent to saying that C ++ mostly treats references as pointers, pointers as references to a variable, and vice versa. They are similar, but different in practice, as the example of the function. In practice, when you have a data string in memory, ask for a pointer. If you need a change in memory variable, ask for a reference. The cleaner a code is, the less chance of making a mistake will exist.

Example:

void f(int&&);
int main()
{
    int var;
    int& referencia = var;
    referencia = 1; // o valor de var agora é 1
    std::cout << (int)&referencia; //imprime o endereço em que var se encontra, dando o ponteiro para a variável
    &referencia = (int*)0; // ERRO: imutável
    f(1); //imprime 1, valor literal
    f(referencia); // ERRO
}

void f(int&& var)
{
    std::cout << var;
}
    
13.01.2016 / 21:25
0

A reference is "safe": it can not be null and the compiler ensures that it points to a valid object. You can not simply declare a variable

Objeto &x;

Because then the variable would be null or invalid. The statement must include the definition:

Objeto y = Objeto();
Objeto &x = y;          // x e y são o mesmo objeto

In a class, you can declare a member that is a reference, but you must use the "member initialization list" syntax to ensure that the member is already valid when the constructor body begins to roll:

class Bla {
   Objeto &x;
   Bla(Objeto &param): x(param) {
       ... 
   }
};

Note that in order to start member x, a reference to Object had to be sent as a parameter to the constructor because a valid reference has to go somewhere, it does not materialize out of nothing.

Object references, as well as object pointers, allow the use of polymorphism. If OtherObject is a subclass of Object, the following syntax is valid:

OutroObjeto y = OutroObjeto();
Objeto &x = y;

Pointers can be null (which is sometimes an advantage), can point to objects that have already been freed from memory, and can even point to arbitrary memory locations, using insecure casts.

If there is no specific reason for using pointers and / or objects allocated with new, it is always better to use references to objects created in stack.

    
09.06.2016 / 08:23