gpt4 book ai didi

c++ - 从 const 成员函数返回的对象的常量性

转载 作者:行者123 更新时间:2023-11-30 04:40:39 25 4
gpt4 key购买 nike

关于 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 的预期常量性。

最佳答案

拥有任何常量比你在许多语言中所能找到的都要多!

一旦您理解(正如您所理解的那样)“物理常量”和“逻辑常量”之间的区别,那么“模棱两可”的场景就仍然存在:有待商榷。例如考虑 mutable 关键字存在的事实。

我认为您的总体想法是正确的:除此之外,所有这些都是有争议的和主观的,并且会根据特定问题和约束等而有所不同。

我倾向于“没有异常(exception)”,所以我会避免从 const 方法返回指向非常量的指针;但我想我可以想象一些我可能会被诱惑的场景……尽管我可能更有可能决定使该方法成为非常量。

关于c++ - 从 const 成员函数返回的对象的常量性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com