问题描述
const
在顶级限定符在C ++中是什么意思?
其他级别是什么?
例如:
int const * i;
int * const i;
int const * const i;
顶级const限定符会影响对象本身。其他只有
与指针和引用相关。他们不使对象
const,并且只阻止通过使用指针或
引用的路径进行修改。因此:
char x;
char const * p =& x;
这不是顶级的const,并且没有对象是不可变的。
表达式 * p
不能用于修改 x
,但是其他表达式
; x
不是常数。
* const_cast< char *>(p)='t'
$ c $
但
char const x ='t';
char const * p =& x;
此时, x
,因此 x
是不可变的。不允许
表达式更改它(即使使用 const_cast
)。
编译器可以在只读存储器中放置 x
,并且可以假定 x $
要给指针顶层 const
,您可以这样写:
char x ='t'
char * const p =& x;
在这种情况下, p
x
forever;任何尝试改变这个
是未定义的行为(并且编译器可以将 p
放在只读存储器中,
或假设 * p
是指 x
,无论其他任何代码)。
What does const
at "top level" qualifier mean in C++?
And what are other levels?
For example:
int const *i;
int *const i;
int const *const i;
解决方案 A top-level const qualifier affects the object itself. Others are onlyrelevant with pointers and references. They do not make the objectconst, and only prevent modification through a path using the pointer orreference. Thus:
char x;
char const* p = &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 expressionscan be; x
is not const. For that matter
*const_cast<char*>( p ) = 't'
is legal and well defined.
But
char const x = 't';
char const* p = &x;
This time, there is a top-level const on x
, so x
is immutable. Noexpression is allowed to change it (even if const_cast
is used). Thecompiler may put x
in read-only memory, and it may assume that thevalue of x
never changes, regardless of what other code may do.
To give the pointer top-level const
, you'd write:
char x = 't';
char *const p = &x;
In this case, p
will point to x
forever; any attempt to change thisis 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限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!