Dereferencing a pointer to constant

前端 未结 10 729
深忆病人
深忆病人 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:59

    Here’s a specific example of why it is the way it is. Let’s say you declare:

    int a[] = {1, 2, 3};
    constexpr size_t n_a = sizeof(a)/sizeof(a[0]);
    
    extern int sum( const int* sequence, size_t n );
    sum_a = sum( a, n_a );
    

    Now you implement sum() in another module. It doesn’t have any idea how the original object you’re pointing to was declared. It would be possible to write a compiler that tagged pointers with that information, but no compilers in actual use today do, for a number of good reasons.¹

    Inside sum(), which might be in a shared library that cannot be recompiled with whole-program optimization, all you see is a pointer to memory that cannot be altered. In fact, on some implementations, trying to write through a pointer to const might crash the program with a memory-protection error. And the ability to reinterpret a block of memory as some other type is important to C/C++. For example, memset() or memcpy() reinterprets it as an array of arbitrary bytes. So the implementation of sum() has no way to tell the provenance of its pointer argument. As far as it’s concerned, it’s just a pointer to const int[].

    More importantly, the contract of the function says that it’s not going to modify the object through that pointer.² It could simply cast away the const qualifier explicitly, but that would be a logic error. If you’re declaring a pointer const, it’s like engaging the safety on your gun: you want the compiler to stop you from shooting yourself in the foot.

    ¹ Including extra instructions to extract the address from a pointer, extra memory to store them, compatibility with the standard calling convention for the architecture, breaking a lot of existing code that assumes things like long being able to hold a pointer, and the lack of any benefit.

    ² With the pedantic exception of mutable data members.

提交回复
热议问题