Does dereferencing a pointer from const_cast ALWAYS cause undefined behavior?

See the following:

struct A { std::string* get() const { //return const_cast<std::string*>(&m_pObj); return &const_cast<A*>(this)->m_pObj; } std::string m_pObj; }; 

const_cast dereferencing const_cast of this UB called? Is there any dereferencing of the result from const_cast from the pointer constant does not cause UB?

(I know that the above example is bad practice, poor design and can be resolved with mutable - this is not the point)

+3
c ++
Jun 15 2018-12-15T00:
source share
4 answers

Does const_cast dereference cause this UB? Is there time for dereferencing the result from const_casting, then the pointer constant does not far call UB?

Not always, only if the object const (instance A - const A x; ) and dereferencing is used to modify data. If it is used only for reading, it will not be undefined behavior, if the object is not constant (maybe not at all, maybe it refers to a const reference to a non-constant object), it will not be UB either.

+9
Jun 15 '12 at 15:45
source share

No, it is only UB if the reference object was declared as const initially and you subsequently modify the data received by the cast (§5.2.11 / 7 and §7.1.6.1 / 4). The following is legal:

 A a; a.get()->clear(); 

while this isnt (and therefore UB):

 A const a; a.get()->clear(); 
+3
Jun 15 2018-12-15T00:
source share

No. To wit:

5.2.2 function call

5 [Note: the function can change the values ​​of its non-constant parameters, but these changes cannot affect the values ​​of the arguments, except when the parameter has a reference type (8.3.2); if the reference is to a const-qualified type, const_cast is required to use the argument value to discard the constant for modification. If the parameter is a const reference type, then a temporary object is entered if (7.1.6, 2.14, 2.14.5, 8.3.4, 12.2). In addition, you can change the values ​​of volatile objects through the parameters of the pointer. -end note]

However

5.2.11 Const cast

12 [Note: some conversions that include only changes to cv-qualification cannot be performed using const_cast. For example, conversions between function pointers are not covered, because such conversions lead to values ​​whose use causes undefined behavior. For the same reasons, conversions between pointers to a member of a function and, in particular, conversion from a pointer to a function of a const member to a pointer to a non-const member function are not covered. -end note]

+1
Jun 15 2018-12-15T00:
source share

The compiler can freely store the value of const in read-only memory; it can make assumptions that it will never change during program optimization. If you drop the constant, you break the contract with the compiler, so technically everything can happen.

Actually, the compiler rarely does something that will be violated by const_cast-ing, but theoretically it is possible.

0
Jun 15 2018-12-15T00:
source share



All Articles