7

我一直试图理解,当我在 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呢?那不会

4

4 回答 4

5

“当我编写一个带有 const 参数的函数时,我的逻辑建议该参数中的任何内容都应该继承 const 性,因为这应该是 const 的目的,以保护基础数据不被修改。”

您对此非常正确,但是存储在X-object内部的指针指向对象外部。外部不受Xconstness 的影响,只是内部存储的数据X

于 2015-08-05T13:34:22.000 回答
2

为什么你认为,因为指针是常数,指向的应该是常数?它不一定遵循。

有时您需要一个必须始终指向特定位置的指针,但您可以通过它修改指定的位置。没有任何class X迹象表明您不应该将内存data点更改为。

更重要的是,您错误地考虑了 const 关键字。给定

X& operator=(const X& other)

您所做的只是告诉编译器您不打算在other内部进行更改,operator=()并要求编译器阻止您这样做,以防您忘记了。不多也不少。它完全没有说明other外部的operator=()const 性,也没有说明任何内部指针指向的任何东西的 const 性other

于 2015-08-05T15:12:02.870 回答
0
int* const other_pointer
declare other_pointer as const pointer to int

相对于:

const int* other_pointer
declare other_pointer as pointer to const int

http://cdecl.org/提供

请注意 const 的位置差异。

于 2015-08-05T13:01:12.487 回答
0

您没有更改 的值other.data,因此没有const违规。您当然可以修改other.data指向的对象,但这超出了编译器强制执行 const 正确性的责任。

于 2015-08-05T14:28:18.993 回答