即使可以将返回的(指针)数据成员用于该方法的“外部”以更改其引用对象,将方法标记为const是否被认为是不好的做法?
看一下bone()方法。
class SceneNode
{
public:
SceneNode(const char *nodeName, SceneNode *parent);
~SceneNode();
void setBone(Bone *bone);
Bone* bone() const { return _bone; }
};
private:
Bone *_bone;
};
我问这个问题是因为对我来说有点奇怪,因为如果_bone不是指针而是对象,则该方法不能为const(当然,除非它返回const引用或副本)。
它取决于,例如,unique_ptr::operator*()
被标记为const,但不会在其返回的引用中添加其他const。这是有道理的,因为它类似于能够修改a指向的内容,T *const
但不能更改指针本身。
const std::unique_ptr<int> uptr(new int); // make_unique is better
*uptr = 1; // sure, I can modify what it points to
uptr.reset(); // no, this modifies the pointer itself (conceptually)
另一方面,诸如std::string
拥有char& operator[](size_t) const;
这样的东西会很奇怪,因为其中的char
s应该像它们所引用的对象的一部分一样起作用(string
类)
const std::string s{"hello world"}; // I expect this to always be "hello world"
s[0] = 'a'; // error, you're conceptually modifying the string
由您决定在API中什么才有意义,以及何时类是“道德常量”。如果你有
void fun(const SceneNode& node);
int main() {
SceneNode n(...);
Bone b;
n.setBone(&b);
fun(n);
assert(*n.bone() == b); // is this a safe assumption?
}
如果您认为断言应始终成立,请返回const Bone*
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句