我一直试图理解,当我在 C++ 中使用常量参数和该对象内部的指针变量编写函数时,const 标志并不能保护底层内存不被修改。例如,在operator=()
名为 的类的函数中执行以下操作是完全合法的X
:
class X
{
public:
X& operator=(const X& other)
{
this->data = other.data; //(*)
return *this;
}
private:
int* data;
};
(*):这与以下相同:
int* some_pointer;
int* const other_pointer = some_pointer;
int* class_pointer = other_pointer;
但不一样:
const int* other_pointer;
int* class_pointer = other_pointer;
这将产生以下错误:
error: invalid conversion from 'const int*' to 'int*' [-fpermissive]
int* class_pointer = other_pointer;
^
我理解为什么other.x
被强制转换为 aint* const
但我不明白为什么它没有同时被强制转换为 a const* int
(即 a const int* const
)。当我编写带有const
参数的函数时,我的逻辑建议该参数中的任何内容都应该继承 constness,因为这应该是 的目的const
,以保护基础数据不被修改。
当从类的版本之外访问指针成员时,const
我认为应该合理地期望对象的const
关键字应该保护从类中脱离出来的任何东西(甚至是内存)不被修改。反对这一点的论点是外部内存不属于该对象,因此保护它也不应该是它的责任。我的观点是,在这种情况下(在任何其他情况下,当它被其他地方以任何类型的访问权限访问时)我们正在从const
对象中取出一些东西。换句话说,它让人们看到了自身之外的东西。那么不引起关注的原因是什么const
呢?那不会