C ++ reference study notes Lesson

Study Notes content from: Ditai Software College Tangzuo Lin teacher's video, I appreciate your guidance

1. The reference is an alias for a variable, is but a memory space of code
2. If a non-read-only variable that already exists has to make a read-only property, only need to define a new variable as a const reference to it, the the new variable is read-only
3. when using literal reference to a const was initialized, c ++ compiler will allocate space to a constant value, and as this memory space reference name alias, i.e. the segments that will be used const reference memory, the value of the symbol table when not going to take but to take the memory section
4. when using a reference when referring to initialize another new references with another reference to the representative of the aliases for the same period of memory space, taking the address the same result

Sample program:
(1)

int a = 0;

const int& b = a;

int* p = (int*)&b;

b = 5;//Error,b是只读变量

*p = 5;//Ok,修改变量a的值

(2)

const int& b = 1;

int* p = (int*)&b;

b = 5;//Error,只读变量

*p = 5;//Ok,修改变量b所对应的内存空间的值

There is no reference in its own memory space it? (Have)

Sample program:
(1)

#include <stdio.h>

struct TRef
{
char& r;
};

int main()
{
char c = 'c';
char& rc = c;
TRef ref = {c};

printf("sizeof(char&) = %d\n",sizeof(char&));  //1
printf("sizeof(rc) = %d\n",sizeof(rc));  //1

printf("sizeof(TRef) = %d\n",sizeof(TRef));  //4
printf("sizeof(ref.r) = %d\n",sizeof(ref.r));  //1

return 0;
}

It cited the nature of: pointers, so the third print is 4 (because it has not initialized who references, so print out is the size of a pointer)

Cited in C ++ implementation is an internal pointer constant
Type & name; -> Type * const name;

Published 15 original articles · won praise 0 · Views 108

Guess you like

Origin blog.csdn.net/u012321968/article/details/104449958