Talk briefly about Pointers and references in C++

  • 2020-04-02 03:21:45
  • OfStack

Pointers and references are very different, but they seem to have the same function, both of which can directly refer to an object and directly manipulate it. But when to use Pointers? When do you use a reference? It's easy to confuse the two, so I'm going to go into the details of Pointers and references to try to show you the real thing. If my spray is not good enough, I hope the mouth under the mercy, hand life, also please point out a thing or two; If you feel good, please clap.

Pointer to the different types of difference is that a pointer type compiler can know explain a particular address (the address pointer to) content and size of the memory and void * pointer is only represents a memory address, the compiler can't pass the pointer points to the object's type and size, so want to void * pointer action object type transformation must be conducted.

u similarities:

1. The concept of address;
    Pointer to a block of memory whose contents are the address of the memory;
    A reference is an alias name for a block of memory.

Taken the difference:

1. A pointer is an entity, and a reference is an alias;
2. References need not be dereferenced (*) when used, and Pointers need to be dereferenced;
3. A reference can only be initialized once at definition time and cannot be changed later; Pointer variable;
    Quote "from one to the end" ^_^
4. Reference without const, pointer with const, const pointer immutable;
5. References cannot be null, Pointers can be null;
6. "sizeof reference" gets the sizeof the referenced variable (object), while "sizeof pointer" gets the sizeof the pointer itself (the address of the referenced variable or object).
Typeid (T) == typeid (T&) is always true, sizeof (T) == sizeof (T&) is always true, but when the reference is a class member name, it takes up the same 4 bytes as the pointer (no standard specification was found).
7. Pointer and reference of the self-increment (++) operation meaning is not the same;

Contact u

1. References are implemented with Pointers within the language (how?) .
2. For general applications, there is no serious semantic error in understanding a reference as a pointer. A reference is a pointer that is operationally restricted (only content fetching is allowed).
References are a concept in C++, and beginners tend to confuse references with Pointers. In the following program, n is a reference of m, and m is the referent.
Int m;
Int &n = m;
N is the alias (nickname) of m, and any operation on n is an operation on m. For example, there is wang xiaomao, whose nickname is "three hairs". Say "three hairs" how how, in fact is to wang xiaomao say three words four. So n is neither a copy of m, nor a pointer to m, but n is m by itself.

Some of the rules cited are as follows:
(1) the reference must be initialized when it is created (the pointer can be initialized at any time).
(2) there cannot be a NULL reference, which must be associated with a valid storage location (the pointer can be NULL).
(3) once the reference is initialized, the relationship of the reference cannot be changed (the pointer can change the referred object at any time).

In the following sample program, k is initialized as a reference to I. Statement k = j does not modify k to be a reference to j, only to change the value of k to 6. Since k is a reference to I, the value of I also becomes 6.


int i = 5 ; 
int j = 6 ; 
int &k = i ; 
k = j ;  //Both k and I become 6;

The above program looks like a word game and does not show the value of the reference. The main function of the reference is to pass the arguments and return values of the function.

Pointers can manipulate things in memory without constraints, and while Pointers are powerful, they are dangerous.
Like a knife, it can be used to cut trees, cut paper, manicure, haircut, etc., who dare to use it?
If you really only need to borrow the "alias" of an object, use "reference" instead of "pointer" to avoid accidents. For example, someone needs a proof that the seal of the official seal should have been stamped on the document. If the key to the official seal is given to him, then he has gained the right that he should not have.

Pointers and references in the More Effective C++ terms are described in detail, I'll turn it around for you

Clause 1: distinction between pointer and reference

Pointers and references look completely different (Pointers use the operators' *' and '-' > ', using the operator '. '), but they seem to have the same function. Pointers and references both allow you to indirectly refer to other objects. How do you decide when to use Pointers and when to use references?
First, realize that under no circumstances should a reference to a null be used. A reference must always point to some object. So if you take a variable and make it point to an object, but the variable may not point to any object at some point, you should declare the variable as a pointer, because then you can assign a null value to the variable. Conversely, if the variable definitely points to an object, such as if your design does not allow the variable to be empty, you can declare the variable as a reference.
"But wait a minute," you ask incredulously. "what are the consequences of this code?"

It is very harmful, no doubt about it. The result will be inconclusive (the compiler can produce some output that makes anything possible), and anyone who writes such code should be avoided unless they agree to correct the error. If you're worried that such code will end up in your software, you'd better avoid references altogether, or let better programmers do it. We will later ignore the possibility that a reference points to a null value.

Because the reference will definitely point to an object, in C++ the reference should be initialized.
String & rs; // error, reference must be initialized
String s ("xyzzy");

String & rs = s; // correct, rs points to s

Pointers have no such limitation.

String * ps; // uninitialized pointer

// legal but dangerous


The fact that there are no references to null values means that code using references is more efficient than using Pointers. Because you don't need to test the validity of a reference before you use it.


void printDouble(const double& rd)
{
 cout << rd; //There is no need to test rd, it
} //It definitely points to a double

Instead, Pointers should always be tested to prevent them from being null:


void printDouble(const double *pd)
{
 if (pd)
 { //Check for NULL
    cout << *pd;
 }
}

Another important difference between a pointer and a reference is that a pointer can be reassigned to point to a different object. But the reference always points to the object specified at the time of initialization and cannot be changed later.


string s1("Nancy");
string s2("Clancy");
string& rs = s1; //Rs reference s1
string *ps = &s1; //Ps to s1
rs = s2; //Rs still refers to s1,
//But the value of s1 is now zero
// "Clancy"
ps = &s2; //Ps is now pointing to s2;
//S1 has not changed

In general, you should use Pointers in the following situations,
One is that you allow for the possibility of not pointing to any object (in which case, you can set the pointer to null),
The second is that you need to be able to point to different objects at different times (in this case, you can change the pointer). If you always point to an object and don't change the point once you point to an object, you should use a reference.
Another case is when you overload an operator, you should use a reference.
The most common example is the operator []. This operator is typically used to return a target object that can be assigned a value.
The vector < int > V (10); // set up a vector with a size of 10;
// vector is a template in the standard C library (see article 35)
V [5] = 10; // the target object to be assigned is the value returned by the operator []
If the operator [] returns a pointer, the following statement must be written:
* v [5] = 10;

But that makes v look like a vector pointer. So you choose to have the operator return a reference. (there is an interesting exception, see article 30)
You shouldn't use Pointers when you know you have to point to an object and don't want to change its pointing, or when overloading the operators and preventing unnecessary semantic misunderstandings. In other cases, you should assume you have a pointer


void func(int* p, int&r);
int a = 1;
int b = 1;
func(&a,b);

The value of the pointer itself is passed by value, you can change the address value, but it doesn't change the value of the variable that the pointer is pointing to,


p = someotherpointer ;  //a is still 1

But you can change the value of the variable that the pointer is pointing to,


*p = 123131 ;  // a now is 123131

But the reference itself is passed by reference, and changing its value means changing the value of the variable corresponding to the reference


r = 1231 ;  // b now is 1231

Use references when possible and Pointers when necessary.

When you do not need to "repoint", references are generally selected before Pointers. This usually means that it is more useful to refer to the public interface of a class. The typical case where a reference occurs is on the surface of an object, and a pointer is used inside the object.

The exception mentioned above is when a function's argument or return value requires a "critical" reference. It is usually best to return/get a pointer and use a NULL pointer for this particular purpose. The reference should always be an alias to the object, not a NULL pointer that is dereferenced.


Related articles: