References and pointers than macro - references and pointers (a)

table of Contents

 

The key variable references of general rules

Common error parameters cited

What is the difference between references and pointers?

Why safer than a reference pointer?


The key variable references of general rules

  • Reference type variable must be initialized at the same time declared
  • In a statement quoted only when they were assigned, and can not be referenced later then the name as a reference to the name of the other variables

  • Uninitialized pointer variable is the field guide

Common error parameters cited

For constant type of variable, which must be a constant reference in the type, amount for the very types of variables, which can be a constant reference types, it can be very quantity type. But no matter what the circumstances, can not be used to modify variables constant references cited value.

#include <stdio.h>
#include <iostream>

int main()
{
	const int a = 10;
	//int &b = a; 报错,不能用一个非常量的引用去引用一个常量
	const int &b = a;
	int c = 4;
	const int &d = c;//可以用一个常量去引用一个非常量的变量

	//b++; //只要常量引用,就不能用其修改被引用的值
	//d++;
	//a++;
	c++;//这个是被常量引用引用的变量,可以修改值

	printf("c:%d\n", c);
	printf("d:%d\n", c);
	system("pause");
	return 0;
}

Run as follows: 

What is the difference between references and pointers?

  1. Different requirements initialization: the reference must be initialized when it is created, that is a reference to a valid object; and the pointer does not have to be initialized when defined, can be reassigned at any place later, however, before using the pointer, you must loading finished. 
  2. Different properties may be modified: the reference object is a designated Once initialized, it can not be changed to another variable references, and the pointer may point to the variable changes.
  3. NULL reference does not exist: NULL pointer is present, but there is a reference to a reference value NULL. Therefore, reference must rely on specific variables, objects and living, and the pointer can not rely on any of them exist.
  4. Application of difference: Once an object is not going to change the point to point, and then use the reference; if there are points to NULL, want to change a different point objects at different times, you need to use the pointer.

Summary: the language level, and use the same object reference; the binary level, referenced by a pointer is to achieve, but the compiler to help us complete the conversion. Overall, the efficiency of both a reference pointer, but also easy and intuitive to use variables.

Why safer than a reference pointer?

Reference does not exist is empty, once the reference must be to bind a specific target can not be changed.

Pointer significantly less "specificity", not only with the change object points, even empty, relatively more secure.

Published 271 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_17846375/article/details/104945098