防止const成员函数更改成员数组 [英] Preventing a const member function from changing a member array
问题描述
显然,仍然允许使用const成员函数更改类成员指向的数据。这是我的意思的示例:
Apparently, a const member function is still allowed to change data that the class member are pointing to. Here's an example of what I mean:
class MyClass
{
public:
MyClass();
int getSomething() const;
private:
int* data;
};
// ... data = new int[10];, or whatever
int MyClass::getSomething() const
{
data[4] = 3; // this is allowed, even those the function is const
return data[4];
}
我希望这样做是不允许的。我应该如何定义数据,以便不允许 getSomething()const进行更改? (但是允许非const函数更改它。)对此是否存在某种最佳实践?也许是std :: vector?
I'd prefer if this was not allowed. How should I define "data" so that "getSomething() const" isn't allowed to change it? (but so that non-const functions are allowed to change it.) Is there some kind of "best practice" for this? Perhaps std::vector?
推荐答案
在 const
成员函数中, 数据
的类型从 int *
更改为 int * const
:
In a const
member function, the type of data
changes from int*
to int *const
:
int * const data;
这意味着指针是 const
在const成员函数中,而不是指针指向的数据本身。因此,您无法执行以下操作:
which means, it's the pointer which is const
in the const member function, not the data itself the pointer points to. So you cannot do the following:
data = new int[100]; //error
,因为它试图更改指针本身,即const,因此是不允许的,但是以下允许:
as it's attempting to change the pointer itself which is const, hence disallowed, but the following is allowed:
data[0] = 100; //ok
因为更改内容不会更改指针。 data
指向相同的内存位置。
Because changing the content doesn't change the pointer. data
points to same memory location.
如果使用 std :: vector< int> ;
,那么您可以实现自己想要的。实际上,矢量解决了这个问题,并因此解决了内存管理问题:
If you use std::vector<int>
, then you can achieve what you want. In fact, vector solves this problem, along with the memory management issues, therefor use it:
class MyClass
{
public:
MyClass();
int getSomething() const;
private:
std::vector<int> data;
};
MyClass::MyClass() : data(10) {} //vector of size 10
int MyClass::getSomething() const
{
data[4] = 3; // compilation error - this is what you wanted.
return data[4];
}
尽可能避免使用非RAII设计。 RAII是解决内存管理问题的出色解决方案。在这里,您可以实现自己想要的。阅读此内容:
Avoid non-RAII design as much as you can. RAII is superior solution to memory management issues. Here, with it, you achieve what you want. Read this:
- Resource Acquisition Is Initialization (RAII)
这篇关于防止const成员函数更改成员数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!