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;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
This is not a top-level const, and none of the objects are immutable.
The expression
*pcannot be used to modifyx, but other expressionscan be;
xis not const. For that matteris legal and well defined.
But
This time, there is a top-level const on
x, soxis immutable. Noexpression is allowed to change it (even if
const_castis used). Thecompiler may put
xin read-only memory, and it may assume that thevalue of
xnever changes, regardless of what other code may do.To give the pointer top-level
const, you’d write:In this case,
pwill point toxforever; any attempt to change thisis undefined behavior (and the compiler may put
pin read-only memory,or assume that
*prefers tox, regardless of any other code).