Re: Using a macro to simplify implementing non-const methods in terms of const overload
On 25 Aug., 17:57, "Chris Morley" <chris.mor...@lineone.net> wrote:
[...] Why don't you put the implementation in the non-const member
function & then simply return that for the const one?
e.g.
class foo
{
public:
std::string& bar() {return bar_;}
const std::string& bar() const {return bar();}
private:
std::string bar_;
};
It compiles. But it doesn't do what you think. It's an infinite
recursion. You get the behaviour you want by writing
class foo
{
public:
std::string& bar() {return bar_;}
const std::string& bar() const
{
return const_cast<foo*>(this)->bar();
}
private:
std::string bar_;
};
But that's really a very bad idea because
(*) it's easier to accidentally violate const correctness
(*) if you accidentally modify something in the non-const version
of bar() you will invoke undefined behaviour in cases like
const foo f; // f is really const!
f.bar(); // Ooops!
Actually, I wrote a KD-tree data structure with a multimap-like
interface a couple of weeks ago. I wanted to have a nearest-neighbour-
search in both versions: const and non-const. It looks like this:
class kdtree_node
{
...
value_type const* nnsearch(point_type const& p,
Real & maxssd) const;
value_type * nnsearch(point_type const& p,
Real & maxssd)
{
kdtree_node const* const me = this;
value_type const* const ret = me->nnsearch(p,maxssd);
return const_cast<value_type*>(ret);
}
...
};
It's not pretty but IMHO reasonably safe. I wonder how std::map::find
is implemented...
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]