Can a heap-allocated object be const in C++?

后端 未结 6 1773
轮回少年
轮回少年 2020-12-08 11:46

In C++ a stack-allocated object can be declared const:

const Class object;

after that trying to call a non-const method on suc

6条回答
  •  悲&欢浪女
    2020-12-08 12:10

    In your heap example, new returns a pointer to non-const. The fact that you've stored it in a pointer to const (and then const_casted it back to a pointer to non-const) doesn't change the fact that the object itself is not const in the same way as the stack-allocated one is.

    However, you can create a const object on the heap:

    const Class* object = new const Class();
    

    In such a case, casting to a pointer to non-const and calling a non-const method would be the same situation as the const stack-allocated object.

    (The idea of creating a const object on the heap was new to me, I had never seen that before. Thanks to Charles Bailey.)

提交回复
热议问题