Re: would you consider this function const?
On 12/15/2011 9:30 AM, john wrote:
One of the issues that spurred this question (related to my func1 in the
original post) is the following. I have a 3D mesh composed of
Volumes/Faces/Edges/Vertices. So, I have a Volume, Face, Edge, and
Vertex class, each derived from a base Topology class. The mesh is
consistent, so given a particular instance of one of the classes, there
are functions that return geometry information such as connectivity. In
particular, each class has a virtual function (declared as pure virtual
at the base Topology class)
virtual void GetVolumes(std::set<Volume*> volumes);
That doesn't look right. Did you lose the ampersand before the argument
name?
Yes, it should be
virtual void GetVolumes(std::set<Volume*>& volumes);
that returns a list of pointers to the volumes associated with the
entity. I want to make this function 'const' since it does not change
the element. For a Face, Edge, and Vertex, this poses no problem.
However, for a volume instance, the function should return a pointer to
just itself, so if GetVolumes is const, then I have
void Volume::GetVolumes(std::set<Volume*> volumes) const
{
volumes.clear();
volumes.insert(const_cast<Volume*>(this));
}
I do not see how to have the GetVolumes function const without the use
of const_cast in the Volume::GetVolumes function. Is there a more
intelligent way to get the same result?
What happens if you change the type of the argument to
std::set<const Volume*>
? If it's a set of constant volumes, that's what the type should
express. If you find it difficult to type, use a typedef *or* introduce
some kind of 'Volume proxy' and keep that instead of the pointer to
Volume.
I will have to look at whether I can do that or not. My guess is that,
for the most part, I will need non-const Volume*'s. It's a huge code
base, so a change like that could ripple to a lot of places.
Well, depending on the domain and the purpose for which the pointers are
collected, it might be OK to const_cast them like that. After all, it
is unlikely that any object of your Volume class is ever created in a
constant memory, so the 'const' here is just a pretense. Keep in mind,
however, that const_cast can be abused. And don't abuse it. If you can
rework your design in such a way that wouldn't call for the use of
'const_cast' to cast *away* any constness, it could lead to a more
robust system, methinks.
I wonder (not that you need to explain, just wonder along with me), how
is Volume and, say, Edge derive from the same class. What is common
about them (aside from 'GetVolumes')? Also, can you have nested
Volumes? You know, an egg inside a duck inside a hare hidden in a
trunk... Seems like if your answer is 'no', then a Volume cannot derive
from Topology since you essentially make Topology aware of a type that
will be derived from it, which is usually a no-no...
V
--
I do not respond to top-posted replies, please don't ask