G
Guest
Hello,
I know the rules for const handling in C++, but I'd like to ask what is
the "right" way to use them, eg. when is it appropriate to make a member
function const?
This came across this question when I was thinking about implementation
of a class implementing some lazy data structure or cache. The C++ rules
allow among other possibilities making all member functions non-const,
or making all member functions const and all members mutable. These are
the extreme possibilities, but in cases I was thinking about, the
differences are more subtle. Imagine, for example, a lazy data
structure, like the union-find data structure with path compression.
This data structure maintains a partition of some set and has two major
operations:
1. union: for two representatives of subsets in the partition, alter the
data structure so the partition contains all subsets except the two,
which are replaced by their union.
2. find: for a member of the set, find a representative of the subset it
is in.
From this description, it may seem that union is non-const and find is
const. But if you look at the implementation, the find alters the data
structure. So is it const or not?
Is const more like "doesn't touch the inner state of the object" or "you
won't notice the state changed"?
What is the compilers' view on this? Do they use const to make some
optimizations? Is there any danger to use cast to remove the const
(which clearly violates the purpose of the const)?
Regards
Jiri Palecek
I know the rules for const handling in C++, but I'd like to ask what is
the "right" way to use them, eg. when is it appropriate to make a member
function const?
This came across this question when I was thinking about implementation
of a class implementing some lazy data structure or cache. The C++ rules
allow among other possibilities making all member functions non-const,
or making all member functions const and all members mutable. These are
the extreme possibilities, but in cases I was thinking about, the
differences are more subtle. Imagine, for example, a lazy data
structure, like the union-find data structure with path compression.
This data structure maintains a partition of some set and has two major
operations:
1. union: for two representatives of subsets in the partition, alter the
data structure so the partition contains all subsets except the two,
which are replaced by their union.
2. find: for a member of the set, find a representative of the subset it
is in.
From this description, it may seem that union is non-const and find is
const. But if you look at the implementation, the find alters the data
structure. So is it const or not?
Is const more like "doesn't touch the inner state of the object" or "you
won't notice the state changed"?
What is the compilers' view on this? Do they use const to make some
optimizations? Is there any danger to use cast to remove the const
(which clearly violates the purpose of the const)?
Regards
Jiri Palecek