常量之间的区别.指针和引用?

2021-12-13 00:00:00 reference pointers c++

常量指针和引用有什么区别?

What is the difference between a constant pointer and a reference?

常量指针顾名思义是不能再绑定的.参考文献也是如此.

Constant pointer as the name implies can not be bound again. Same is the case with the reference.

我想知道在哪种情况下,一种会比另一种更受欢迎.他们的 C++ 标准和实现有何不同?

I wonder in what sort of scenarios would one be preferred over the other. How different is their C++ standard and their implementations?

干杯

推荐答案

const 指针有 3 种类型:

There are 3 types of const pointers:

//Data that p points to cannot be changed from p
const char* p = szBuffer;

//p cannot point to something different.  
char* const p = szBuffer;

//Both of the above restrictions apply on p
const char* const p = szBuffer;

上面的方法#2 与参考文献最相似.

Method #2 above is most similar to a reference.

引用和上述所有 3 种类型的 const 指针之间存在主要区别:

There are key differences between references and all of the 3 types of const pointers above:

  • 常量指针可以为 NULL.

  • Const pointers can be NULL.

引用没有自己的地址,而指针有.
引用的地址是实际对象的地址.

A reference does not have its own address whereas a pointer does.
The address of a reference is the actual object's address.

一个指针有它自己的地址,并且它的值是它指向的值的地址.

A pointer has its own address and it holds as its value the address of the value it points to.

在此处查看 我的回答参考和指针之间的更多区别.

相关文章