A summary of C + + pointers and reference knowledge points

Source: Internet
Author: User

Summary

pointers can point to variables, arrays, strings, functions, and even structs. That is, pointers can point to different data objects. Pointer problems include constant pointers, array pointers, function pointers, this pointer, pointer passing values, pointers to pointers, and so on. Key points of knowledge include: 1. Three differences between pointers and references in concept and their differences in const, sizeof, and self-increment operations ; 2. Memorize the classic Swap function pointer implementation and reference implementation, and can reflect the output error of the two functions of the ideological shortcomings; 3. Memorize the wrong form of the GETMEM function and the cause of the error; 4. Compare arrays, pointers and static variables as function return values; 5.str, *STR, and The relationship between the three &str; 6. The relationship between virtual function, real function and variables in pointer inheritance complex direction ; 7. Write a const pointer to a const pointer, a const pointer to const, 8. Analyze the difference between the high-dimensional array pointer and the high-dimensional array; 9. Distinguish between the hovering pointer and the null pointer; 10.new and malloc FAQs, essential differences, why new, why not propose malloc 11.this Pointer 3 points, why there is this,this when to use, this how to pass to the function; 12. Handle and Smart pointer.

Body

Test point: The difference between a pointer and a reference

    • Pointers need to be tested for legality and references are not required;
    • The pointer can be assigned to re-point to the new object (not the address, not the type), but the reference can only point to the initialization of the specified object that cannot be changed;
    • References should be used when pointing to an object that does not change, and pointers should be applied if there is a change in the object that does not point to any objects or objects;
    • Pointers can point to null values, but references cannot point to null values. Therefore, the programmer may have to point to null values, that is, when the variable is allowed to be empty, the pointer should be used;
    • The code referenced is more efficient than the pointer (specifically, it is possible to not assign a value at initialization time).
"Supplement"
1) The reference does not have a const, the pointer has a const, it should be remembered that the use of the const declaration must be initialized at the same time;
2) Pointer to a piece of memory, its content is the address to be pointed to, referring to the alias of a block of memory;
3) sizeof refers to the size of the variable to which it is pointing, and the size of the pointer itself is obtained by the sizeof pointer;
4) Pointers and references do not have the same meaning as the self-increment operation.
"Example"
int &ref;//error, reference cannot be empty and needs to be initialized at the same time, so error! int *p = 5;//error, pointer position to actual memory space, after assignment do not know stored address, no point, so error! int *ptra,*ptrb;int Ptra = *ptrb;//error, pointer position to actual memory space, after assignment does not know the address that is stored, so error! const INT num;//error, const constant assignment must be initialized at the same time, so error!
Test center : Classic swap (int &a,int &b) function
Pointer mode: Incoming is the address, received the pointer, processing is to change the pointer of the relationship;
Citation: A variable is passed in (that is, swap (int a,int b)), which receives a reference (address, or swap (int &ref_a,int&ref_b)), and deals with changing the point of reference, that is, referring to the variable itself;

Misunderstanding
    • A change in address mode will eventually release the changed results;
    • If the function uses the pointer variable to make the medium, it will cause memory leakage.

Test Center: pointer Request memory space
Function source Code
void Getmema (char *p,int num) {p = (char*) malloc (sizeof (char) *num);}void getmemb (char **p,int num) {*p = (char* ) malloc (sizeof (char) *num);}

Resolution

Because a function cannot pass a value only, it is not successful to request memory space (that is, void Getmem (char *p,int num)) within a function by using a pointer. So we should use pointers to pointers (that is, void Getmem (char **p,int num)) for implementing space applications.

Suppose, in the main () function, the variable p address is 1 to the address 2 (you can imagine the variable P-value is 2), the *p address is 2 to the address is 3 (you can imagine the variable *p value is 3), the **p address is 3 to store a char variable.

in void Getmema (char *p,int num), the function variable is temporarily called GETMEMA.P, and it is clear that GETMEMA.P is an address that points to a char variable. After the function request stack enters the function, the GETMEMA.P address is 4, and the pointer variable obtains a block of char-type memory space of length Num. At the end of the function call, the stack destroys the variable GETMEMA.P and its application space, so the variable p in the main function does not get any change;

in void Getmemb (char **p,int num), the function variable is temporarily called Getmemb.*p, and it is clear that getmemb.*p is an address that points to a char variable. After the function request stack enters the function, the Getmemb.*p address is 5, and the pointer variable obtains a block of char-type memory space of length Num. At the end of the function call, the stack destroys the variable GETMEMB.P and its application space (note that this is the variable GETMEMB.P instead of the variable getmemb.*p), then getmemb.*p naturally retains the requested memory space, the variable p in the main function No change was made, and *p obtained a char-shaped memory space of a length of num;

Of course, functions can also be written like this to directly return memory space.

char* GETMEMC (char *p,int num) {p = (char*) malloc (sizeof (char) *num);}
"source code delivery for integer data"
#include <iostream>using namespace std;void GetMemory2 (int *z) {    *z=5;}; int main () {    int v;    GetMemory2 (&v);    cout << v << endl;    return 0;}
"Note"
In short, changing the variables that the elements in the function refers to can effectively change the value of the variable, and if the element itself is changed, regardless of whether the element is an address or something else, it will be released after the function call ends.

Key knowledge points for strings
Distinguishing between array strings and pointer strings
Char *stra () {    char str[] = "Hello World";    return str;}
parsing:
The address that exists in this STR is the first address of "Hello World" in the function Stra stack. The function call completes, the stack frame restores the state before calling Stra, the temporary space is reset, the stack is "retracted", and the stra stack frame no longer belongs to the scope that should be accessed. This program can output the results correctly, but this access method violates the stack frame mechanism of the function. As long as the other function is called, you will find that this method is unreasonable and dangerous. "Did not understand this sentence. 】
--PostScript
The OS thinks the memory can be used, and the memory content changes or other operations will make the memory no longer properly called by Str.
If you want to get the right function, change it to the following:
Char *stra () {    char *str = "Hello World";    return str;}
The first thing to figure out is Char *str and Char str[]:
Char str[] = "Hello World"; is the allocation of a local array. A local array is a local variable, which corresponds to an in-memory stack. The variable does not exist at the end of the life cycle of the local variable.
char *str = "Hello World"; a string pointing to a constant area, located in the static store, which is constant for the lifetime of the program, so the string is still there. Whenever Stra is called, it always returns the same "read-only" block of memory.
It always returns the same "read-only" block of memory. Important thing to say three times! It always returns the same "read-only" block of memory.
Also, you may want to modify the unreasonable distribution of the above character array variables:
Char *stra () {    static char str[] = "Hello World";    return str;}
creates a static storage space through static.
Answer:
Because this function returns the address of a local variable, when this function is called, the local variable str is released, so the returned result is indeterminate and unsafe, and can be retracted at any time.
"Anyway, the return value cannot be an array, preferably a pointer!" 】


Another

char *str = "Hello";
//Then: *STR = "h"; str = "Hello"; &str = (address)
"another"
char *a[] = {"Hello", "the", "World"};
char **ptra = A;
//ptra++; cout<< *ptra << Endl;//output for the
//cout<< *ptra++ << Endl;//output as Hello
in other words, the priority of ' * ' is higher than ' + + '
the understanding of strings and arrays is described in-depth understanding of string and array;
MSBD. v.4.0-p.69.3 ~ 70.5 ~ 72.7 ~ 73.9-impt!!!

Memory Offset
in memory, two pointers Ptra and PTRB, where the value of (PTRA-PTRB) is not the mathematical difference of the actual address. (assuming that Ptra and PTRB point to integer variables), essentially they are compiled with an operation of (PTRA-PTRB)/sizeof (int).
offset Address, code example
#include ... class a{...} Class b{...} ; int main () {      a A;      B *PB = (b*) (&a);}
"parsing"
This assigns the address of object A to a pointer to a class B object, so the assignment is barbaric. Although, not necessarily error, the result is to force the content of a address as a class B object, Pb points to a class of memory space.
Comparison analysis of value transfer of member variables caused by assignment and inheritance
See: Analysis of the coverage of member variables under C + + class inheritance and object assignment
Detailed Address: http://blog.csdn.net/u013630349/article/details/46722893
offset Address, code example:
#include ... int main () {      int *ptr;      ptr = (int*) 0x8000;      *ptr = Oxaabb;}
Resolution
The code will be run with an error. The intent of this code is to point the 0x8000 memory space to the address of an integer data. Where 0x8000 points to a space storage Oxaa, 0x8001 points to a space storage oxbb. The random assignment of the pointer address is not allowed unless all resources are manipulated by the programmer, otherwise, try to avoid the underlying operation.
offset Address, code example:
#include <iostream>using namespace std;struct s{int i;int *p;} Main () {s s;int *p = &s.i;p[0] = 1;p[1] = 5;cout<< "s address \ T" <<&s<<endl;cout<< "S.I address \ T" & lt;<&s.i<<endl;cout<< "P value \t\t" <<p<<endl;cout<< "p[0" address \ T "<<&p[0 ]<<endl;cout<< "S.P address \ T" <<&s.p<<endl;cout<< "p[1" address \ T "<<&p[1]< <endl;cout<< "s.i value \ T" <<s.i<<endl;cout<< "S.P value \ T" <<s.p<<endl;cout< < "*S.P value \ T" << "error" <<endl;cout<< "S.*p value \ T" << "error" <<endl;cout<< "&s.*p value \ t "<<" error "&LT;&LT;ENDL;S.P = p;cout<<" ************************ "<<endl;cout<<" execute S.P = p; \ t "<<" after "<<endl;cout<<" ************************ "<<endl;cout<<" s address \ T "<< &s<<endl;cout<< "S.I address \ T" <<&s.i<<endl;cout<< "p value \t\t" <<p<< endl;cout<< the land of "p[0"\ t "<<&p[0]<<endl;cout<<" S.P value \ T "<<s.p<<endl;cout<<" S.P address \ T "<< &s.p<<endl;cout<< value of "s.p[0" \ T "<<s.p[0]<<endl;cout<<" s.p[1] \ T "<<s.p[1" <<endl;cout<< "p[1" address \ T "<<&p[1]<<endl;cout<<" p[0 "value \ T" <<p[0]<< endl;cout<< value of "p[1" \ T "<<p[1]<<endl;s.p[1" = 1;cout<< "************************" << endl;cout<< "Execute s.p[1] = 1;\t" << "after" <<endl;cout<< "************************" <<endl; cout<< "S.P =" <<s.p<<endl;cout<< "s.p+1 =" <<s.p+1<<endl;//cout<< "*S.P =" <<*s.p<<endl; Crash
"Code Output"
Address of S address        0018ff40s.i address      0018ff40p value           0018ff40p[0] Address 0018FF40S.P address     0018ff44p[1]   0018FF44S.I value 1S.P value 00000005*S.P value error s.*p value error      &s.*p value error   ************************ Execution S.P = p;    The value of address 0018FF40S.P after ************************s address        0018ff40s.i address      0018ff40p value          0018ff40p[0]     0018FF40S.P value of the address 0018ff44s.p[0] value      1s.p[1] value of     1638208p[1]       The value of 0018ff44p[0]       1638208************************ execution S.p[1] = 1; After ************************s.p = 00000001s.p+1 = 00000005Press any Key to continue
"Code Analysis"
int *p = &s.i;//is equivalent to P = &p[0] = &s = &s.i//and there is p+1 = &p[1] = &s+1 = &s.i+1 = &S.PS.P = P ;//To Know (s.*p) = S.P = p//equivalent has * (p+1) = *&p[1] = *&s+1 = *&s.i+1 = *&S.P = p//Simplified * (p+1) = p[1] = S+1 = S . i+1 = S.P = p//already known p = &p[0] = S.P = &s.p[0]//so there is &p[0] = p[1] and &s.p[0] = s.p[1]s.p[1] = 1//give again at this time, s.p[ 0] or p[0] assignment, which is equivalent to writing a variable in a space with a memory address of 1. Therefore, this sentence is not an error, once the point to the address assignment, it will cause the program to crash.
Test Centers: Various types of pointer representations
Priority Level() > data type (e.g. int, char etc) > [] > * > + +
function Pointersvoid (*ptr) ();
function return pointerint *func ();
Const Pointerconst int *ptr;
Pointer to constint *const ptr;
const pointer pointing to constconst int *const ptr;
an array with 10 pointers pointing to a function that has an integer parameter and returns an integral type
int (*ptr (int)) [Ten]
Int (* (*ptr) (int,int)) (int)
ptr is a function pointer with an input parameter of two integer variables whose return value is a function pointer with an input parameter that returns a value of integral type for an integer variable


Note

How function pointers are declared
...
int Max (int,int);//The maximum function has been obtained
...

int *ptr (int,int) = &max;

See:

C + + high-dimensional pointer arrays and high-dimensional array pointers (i)

C + + high-dimensional pointer arrays and high-dimensional array pointers (ii)

C + + array pointer pointer array and function pointer pointer function

Detailed Address:

http://blog.csdn.net/u013630349/article/details/44998689

http://blog.csdn.net/u013630349/article/details/44195523

http://blog.csdn.net/u013630349/article/details/45098899


"Code Sample"

int a[] = {1,2,3,4,5};

int *ptr = (int*) (&a+1);

printf ("%d%d", * (a+1), * (ptr-1));

Note: * (a+1) directly for 2 simple &a+1 because itself a is an array name is the pointer, plus & equivalent to double pointer is also equivalent to * * (a+1) So add 1 is the whole array plus a row, PTR points to the 6th element of a, so * (PTR-1) 5

See: Array of C + + array pointer pointers and function pointer pointers functions

Detailed Address: http://blog.csdn.net/u013630349/article/details/45098899


Test center : null pointer and hover pointer
A null pointer requests a memory space, but a pointer to NULL or 0, or ptr = 0, at which point the manipulation of the pointer can cause a crash, but it is much easier to debug than a floating pointer;

The hover pointer is a pointer to the memory that was requested, and after a series of operations, the RAM was freed. Although the pointer no longer points to fixed memory, the pointer is still present and points to a random area, which is dangerous for pointer operation.


Test Centers: Malloc/free and New/delete

Differences, comparisons, and analyses of malloc free new Delete

See: Analysis of Malloc/free and New/delete in C + +


Test Center: pointer and handle
Windows uses a handle to mark system resources and hide system information. You just need to know that there is this thing and then go to invoke it, the handle is a 32-bit unsigned integer number.
The pointer is the tag of a physical memory address.

Auto_ptr
Std::auto_ptr <Object> pObj (new Object);
The advantage of auto_ptr is that this pointer will be deleted automatically at the time of destruction, but not misused;
1) cannot share ownership, that is, do not let two auto_ptr point to the same object;
2) cannot point to an array because the delete is called at the time of the destructor, not delete[];
3) cannot be used as a container object;

Test Center: this pointer

See: C + + this pointer analysis

Detailed Address: http://blog.csdn.net/u013630349/article/details/46412485

C + + 's compilation system uses only a space to store the public function code, calling the public function code when invoking the member functions of each object.
The value of the this pointer is the starting address of the object that is currently calling the member function.
One case is to use return *this when returning the class object itself in a non-static member function of the class, and the other is when the parameter uses the this pointer with the member variable name, such as This->num = num (num = num cannot be written).
The this pointer can only be used in member functions. Global functions, static functions cannot use this. The member function defaults to the first parameter of t* const this.
This is passed through the first argument of the function. The this pointer is generated before the call. The function after the class instance, there is no such argument. When a class is instantiated, only the variable space in the class is allocated, and no space is allocated for the function, and the function of the class is there when the definition is complete, and it does not run.

Legacy issues:
"Wild Hands"
Handle
Smart Pointers

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A summary of C + + pointers and reference knowledge points

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.