什么是顶级 const 限定符?

2022-01-23 00:00:00 constants c++

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).

相关文章