What’s the best practice for returning a pointer-to-non-const from a function, where that pointer was obtained by modifying a (non-const) pointer-to-const? Like this:
NODE *top_level(const NODE *input)
{
while (input->parent != nullptr)
input = input->parent; // NODE::parent is (non-const) NODE*
return input; // Compile failure:
// Cannot convert from 'const NODE *' to 'NODE *'
}
I could const_cast the const away on return, which seems fine, but is there a better way?
Best practice, at least in the standard library, is to provide
constand non-constoverloads. E.g.std::strchris declared in<cstring>asIn a similar vein, functions like
std::map<T>::findhave overloads such asNote that that there’s no
constqualifier on the first version, even thoughfinditself has no reason to modify themap.(*) The point is that you get something out offindthat can be used to modify the map, so by a kind of “transitivity of mutability”,findcannot beconst. The same situation applies in your problem, I think.Alternatively, you could use a
const_cast, but to me, that would feel like breaking a promise.The funny thing about this situation is that, if you can guarantee that your function is never called on the top item of the tree (or whatever the input is), then there’s no need for casts or overloads:
compiles without any warnings.
(*) If
std::mapwere implemented as a splay tree,findwould have to modify it, but I don’t think splay trees are allowed by the standard because of complexity guarantees.