Is it safe to remove const via const_cast and invoke a non-const function that does not modify the resulting object?

后端 未结 3 902
悲&欢浪女
悲&欢浪女 2020-12-06 07:03

I know that casting away const-ness should be done with care, and any attempt to remove const-ness from an initially const object foll

3条回答
  •  天命终不由人
    2020-12-06 07:26

    We have this in [dcl.type.cv]:

    Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

    And there is a note (non-normative) in [expr.const.cast] which states:

    [Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]

    An attempt to modify an object or a write operation after a const_cast [may] result in undefined behavior. Here, we have no write operation.

提交回复
热议问题