On Jul 6, 8:15 pm, Luna Moon <lunamoonm...@gmail.comwrote:
I just couldn't get myself clear about the usage of "const" in
front of and/or behind variables, pointers, classes, objects
and functions...
It's too confusing... any good clear article/tutorial that can
help me?
It's not really that complicated. The simplest rule when
writing code is that the const goes behind whatever it's
modifying. In a lot of cases, the language doesn't give you a
choice, so you might as well be consistent. (It also helps in
understanding the effects of const when typedef's are involved.)
Beyond that, const has two more or less distinct meanings. If
it applies to an object, it means that the object itself is
const, and any attempt to modify it is undefined behavior---the
compiler can put it in write only memory, or simply assume that
its value hasn't changed, for optimization purposes. (There is
one exception to this: mutable members of const class type
objects.)
The second involves the way const works in the type system: the
type "int const" is not the same type as "int", and there are
operations which are allowed on an expression of type "int", but
not on an expression of type "int const". As explained above,
if the expression denotes an actual object of the type const,
those operations result in undefined behavior, but of course, a
const type can appear in expressions even when no const object
is involved. Thus, the typename "int const*" refers to a
pointer to a const int, and "int *const" refers to a const
pointer to a (non-const) int: both declare an object of pointer
type, but in the case of the first, this object (the pointer) is
not const; the only role of the const here is in the type
system. The type system also has the concept of a const member
function; in this case, the const affects the type of the this
pointer, which becomes T const*, rather than T*.
Note too that when you define a class yourself, you can more or
less define what "const" means when applied to that class.
Thus, for example, std::vector defines const to mean that you
cannot modify the elements in the vector (or more correctly, the
elements in the vector are also "const", with whatever meaning
const has for them), even though they are separate "objects".
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34