What is a good rule of thumb as to whether or not the return value of a const member function should be const or not? Here's what I tend to do, but I struggle with ambiguous scenarios.
class foo
{
public:
// if the returned object is conceptually
// (and therefore usually literally but not even necessarily)
// owned by *this*,
// then a const ptr should be returned
const ownedByFoo *getOwnedByFoo() const { return m_ownedByFoo; }
ownedByFoo *getOwnedByFoo() { return m_ownedByFoo; }
// what's a poor boy to do here?
// veryRelatedToFoo might be a conceptual contemporary or parent
// of Foo. Note naming the function "find..." instead of "get.."
// since *get* implies the object holds it as a data member but
// that may not even be the case here. There could be a
// standalone container that associates foo and veryRelatedToFoo.
// Should constness be symmetrical here?
const veryRelatedToFoo *findVeryRelatedToFoo() const;
veryRelatedToFoo *findVeryRelatedToFoo();
// If the returned object is only (conceptually)
// peripherally related to *this*,
// the returned object probably shoudn't be const, even if
// foo happens to have one of these as a direct data member,
// since we don't want to give away the implementation details of
// Foo and it may hold peripherallyRelatedToFoo simply for performance
// reasons, etc.
peripherallyRelatedToFoo *findPeripherallyRelatedToFoo() const
...
};
One additional note is that once you have asymmetrical constness, you could ask const object A to return object B, then ask object B to return object A, and then you've managed to bypass the intended constness of object A.