什么是顶级 const 限定符?

What are top-level const qualifiers?(什么是顶级 const 限定符?)
本文介绍了什么是顶级 const 限定符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const at "top level" qualifier 在 C++ 中是什么意思?

What does const at "top level" qualifier mean in C++?

还有什么其他级别?

例如:

int const *i;
int *const i;
int const *const i;

推荐答案

顶级 const 限定符会影响对象本身.其他只是与指针和引用相关.他们不做对象const,并且仅防止使用指针或通过路径修改参考.因此:

A top-level const qualifier affects the object itself. Others are only relevant with pointers and references. They do not make the object const, and only prevent modification through a path using the pointer or reference. Thus:

char x;
char const* p = &x;

这不是顶级常量,并且没有一个对象是不可变的.表达式 *p 不能用于修改 x,但其他表达式可;x 不是常量.就此而言

This is not a top-level const, and none of the objects are immutable. The expression *p cannot be used to modify x, but other expressions can be; x is not const. For that matter

*const_cast<char*>( p ) = 't'

合法且定义明确.

但是

char const x = 't';
char const* p = &x;

这一次,x 上有一个顶级的 const,所以 x 是不可变的.不允许更改它的表达式(即使使用了 const_cast).这编译器可能会将 x 放在只读内存中,并且它可能会假设x 的值永远不会改变,无论其他代码可能做什么.

This time, there is a top-level const on x, so x is immutable. No expression is allowed to change it (even if const_cast is used). The compiler may put x in read-only memory, and it may assume that the value of x never changes, regardless of what other code may do.

要给指针顶层const,你可以这样写:

To give the pointer top-level const, you'd write:

char x = 't';
char *const p = &x;

在这种情况下,p 将永远指向x;任何改变这一点的尝试是未定义的行为(编译器可能会将 p 放在只读内存中,或假设 *p 引用 x,而不管其他任何代码).

In this case, p will point to x forever; any attempt to change this is undefined behavior (and the compiler may put p in read-only memory, or assume that *p refers to x, regardless of any other code).

这篇关于什么是顶级 const 限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)