什么是顶级const限定符? [英] What are top-level const qualifiers?

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

问题描述

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'


  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 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;

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'

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

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 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限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆