Why does const_cast remove constness for a pointer but not for a pointer to a const?

后端 未结 3 924
小鲜肉
小鲜肉 2021-02-05 12:31

I understand that const_cast works with pointers and references.

I\'m assuming that the input to const_cast should be a pointe

3条回答
  •  感情败类
    2021-02-05 13:18

    (2) and (3) has the same principle, so I'll talk about (2) only.

    The line

    const_cast(ri) = 321;
    

    has undefined behavior.

    You cannot modify a const object according to the standard, not even with const_cast. If you remove const from a pointer/reference, and modify the pointed/referenced object, the pointed/referenced object must not been declared as const in the first place.

    const_cast should be used only, when you have a const pointer to something for some reason, and you know that something is not declared as const.

提交回复
热议问题