Dereferencing a pointer to constant

前端 未结 10 559
深忆病人
深忆病人 2020-12-30 23:09

Let\'s say we have a class called object.

int main(){
    object a;
    const object* b = &a;
    (*b); 
}

Question: b is a pointer to

10条回答
  •  有刺的猬
    2020-12-30 23:40

    Because that's how the built-in dereference operator * works in C++. If you dereference a pointer of type T *, you get an lvalue of type T. In your case T is const object.

    Neither * operator, not the pointer itself cares (or knows) that the object the pointer is pointing to is actually non-constant. It just can't be any other way within the concept of static typing used by C++ language.

    The whole purpose of const-qualification at the first (and deeper) levels of indirection is to provide you with an ability to create restrictive access paths to objects. I.e. by creating a pointer-to-const you are deliberately and willingly preventing yourself (or someone else) from modifying the pointee, even if the pointee is not constant.

提交回复
热议问题