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

后端 未结 6 1664
轮回少年
轮回少年 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 11:54

    const_cast can cause UB when the object is actually read-only (for example, the compiler can create such objects when you use hard coded strings in your code, by placing them in certain memory areas that are read only) for some reason. This will not happen with heap allocated objects, no matter how you keep their reference (const pointer, const reference, whatever).

提交回复
热议问题