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

后端 未结 6 1781
轮回少年
轮回少年 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

    Yes, a heap-allocated object can be const. Consider this excerpt from the example in 7.1.5.1/5:

    const int* ciq = new const int (3);    // initialized as required
    int* iq = const_cast(ciq);       // cast required
    *iq = 4;                               // undefined: modifies a const object
    

    The example you gave in the question is fine because you're not asking new to make a const object; you're just storing the result in a pointer-to-const.

提交回复
热议问题