我想问一个关于方法的const-correctness的问题.让我来说明一下情况.
class MyClass
{
public:
...
void DiscussedMethod() { otherClass->NonConstMethod(); }
private:
OtherClass *otherClass;
};
Run Code Online (Sandbox Code Playgroud)
我有一个MyClass保持指针的类OtherClass.在DiscussedMethod它调用OtherClass::NonConstMethod哪些修改一些可见数据.
我想知道,制作DiscussedMethod const(因为它不修改任何成员数据)是否是一个好习惯?这会是一种不好的做法吗?或者两者都很好?
如果有什么OtherClass保留的指针MyClass,并NonConstMethod修改了一些的MyClass"数据(意味着MyClass成员数据会在过程中改变DiscussedMethod呼叫).制作DiscussedMethod const当时的做法是不好的做法?
据我所知,const一个方法主要是代码记录的东西,所以我可能倾向于不做DiscussedMethod const,但我想听听你的意见.
编辑:一些回复考虑了指向的对象是否由对象otherClass拥有MyClass.在我正在使用的场景中情况并非如此.让我们说两个对象并排存在(能够相互修改).我认为这个比喻很好地描述了我的情况.
例如,考虑像双向链表这样的东西,其中每个元素都是一个保持指向其邻居和成员变量的指针的类color.并且它有MakeNeighboursRed改变color其邻居的方法但不影响调用对象的状态本身.我应该考虑制作这种方法const吗?
如果有可能MakeNeighboursRed会打电话给邻居怎么办呢MakeNeighboursRed?因此,最终MakeNeighboursRed调用的对象的状态最初也会改变.
我想感谢大家的意见:-)
如果MyClass拥有该OtherClass实例,我将不会DiscussedMethod保持不变.
类,管理资源也是如此.即标准容器不使用const函数返回非const引用或指向托管内存的指针,尽管它是"可能的"(因为保存资源的实际指针未被修改).
考虑
class MyClass
{
public:
bool a() const { return otherClass->SomeMethod(); }
void b() const { otherClass->NonConstMethod(); }
private:
OtherClass *otherClass;
};
void foo (MyClass const &x)
{
cout << boolalpha << x.a() << endl;
x.b(); // possible if b is a const function
cout << boolalpha << x.a() << endl;
}
Run Code Online (Sandbox Code Playgroud)
在foo可以打印两个不同的值虽然实现者foo可能会期望有两个功能,一个const对象调用将具有相同的行为.
为了澄清:
根据标准,以下内容无效,因为operator[]返回的const版本std::vector<T>::const_reference是对值类型的常量引用.
std::vector<int> const a = { /* ... */ };
a[0] = 23; // impossible, the content is part of the state of a
Run Code Online (Sandbox Code Playgroud)
如果只有这个函数的一个签名,也就是说referece operator[] (size_t i) const;,因为操作不会改变向量的内部指针,而是改变它们指向的内存.
但是由向量管理的存储器被认为是向量状态的一部分,因此通过const向量接口不可能进行修改.
如果向量包含指针,那些指针仍然可以通过公共const向量接口不可修改,尽管存储在向量中的指针很可能是非常量的,并且很可能改变它们指向的内存.
std::vector<int*> const b = { /* ... */ };
int x(2);
b[0] = &x; // impossible, b is const
*b[0] = x; // possible since value_type is int* not int const *
Run Code Online (Sandbox Code Playgroud)