关于const成员函数的返回值是否应该是const或者不是const的一个好的经验法则是什么?以下是我倾向于做的事情,但我很难与 模糊的情景。从const成员函数返回对象的常量
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
...
};
另外一个需要注意的是,一旦你有不对称的常量性,你可以 问const对象A返回对象B,然后问对象B返回对象A,并 那么你已经成功绕过预期对象A的稳定性。
从技术上讲,你说的是正常合同,但这是一种过于字面的解释。当你无意中问一个物体(如在常量中)交出一块自己的物体时,你会得到一个非const对象的装载枪(然后你可以修改你的心)。该方法是一个特洛伊木马进入你的对象。 你的第二点很好。我认为人们通常习惯于重载签名,因为他们可以在const和non-const情况下的任何地方使用相同的get方法,而无需考虑它,但让调用者思考它通常是件好事 – 2009-05-22 20:02:27