關於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