What's the point of const pointers?

后端 未结 17 1931
粉色の甜心
粉色の甜心 2020-11-30 17:28

I\'m not talking about pointers to const values, but const pointers themselves.

I\'m learning C and C++ beyond the very basic stuff and just until today I realized t

17条回答
  •  孤街浪徒
    2020-11-30 17:57

    const is a tool which you should use in pursuit of a very important C++ concept:

    Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

    Even though it doesn't change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

    void foo(int* ptr)
    {
        ptr = 0;// oops, I meant *ptr = 0
    }
    

    If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

提交回复
热议问题