当我在 C++ 中编写一个带有常量参数和该对象内部的指针变量的函数时,我一直在努力理解,而不是 const 标志不保护底层内存免受修改。
例如,在名为 X
的类的 operator=()
函数中执行以下操作是完全合法的:
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
被转换为 int* const
但我不明白为什么它没有被转换为 const * int
同时(这是一个 const int* const
)。当我使用 const
参数编写函数时,我的逻辑建议该参数中的任何内容都应继承常量,因为这应该是 const
的目的,以保护底层数据不被修改.
当从类的 const
版本外部访问指针成员时,我认为对象的 const
关键字应该保护任何东西(甚至内存)从修改中脱离类。反对这一点的论点是外部内存不属于该对象,因此保护它也不应该是它的责任。我对此的看法是,在这种情况下(在任何其他情况下,当它在其他地方以任何类型的访问权限访问时)我们正在从 const
对象中取出一些东西。换句话说,它使自身之外的事物可见。那么不使可见性 const
背后的原因是什么?这不会改变代码任何其他位置的内存的可访问权限!
最佳答案
"When I write a function with a const argument my logic suggests anything inside that argument should inherit the constness because that should be the purpose of const, to protect the underlying data against modification."
您对此非常正确,但是存储在 X
对象内部的指针指向对象外部。外部不受 X
的常量影响,仅受 X
内部存储的数据影响。
关于c++ - 为什么C++允许从外部修改一个常量对象的指针成员变量的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31833209/