Why is it written to an object that is not a const object after you select the const pointer to this object, and not UB?

According to the C ++ standard, you can drop constfrom the pointer and write to the object if the object was not originally const. To this:

 const Type* object = new Type();
 const_cast<Type*>( object )->Modify();

ok but this is:

 const Type object;
 const_cast<Type*>( &object )->Modify();

- UB. The reason is that when the object itself const, the compiler is allowed to optimize access to it, for example, not to perform repeated readings, since repeated readings do not make sense to an object that does not change.

The question is how the compiler will know which objects actually are const. For example, I have a function:

void function( const Type* object )
{
    const_cast<Type*>( object )->Modify();
}

and it is compiled into a static lib, and the compiler has no idea what objects it will be called for.

:

Type* object = new Type();
function( object );

, :

const Type object;
function( &object );

undefined.

? , ?

+5
5

: " , ?" , , - - , - . undefined , .

. f() 10, EvilMutate, cobj.member cobj, . g(), const. EvilMutate member cobj f() undefined, , - .

, const , , undefined; , , , .

struct Type {
    int member;
    void Mutate();
    void EvilMutate() const;
    Type() : member(10) {}
};


int f()
{
    const Type cobj;
    cobj.EvilMutate();
    return cobj.member; 
}

int g()
{
     Type obj;
     obj.EvilMutate();
     return obj.member; 
}
+5

const, / const (. ). function, const Type. , , ( function) , (, ) ( )

, , .

+3

const, , - - . const , , , , . const -ness , , .

, , , const , , , , const ( , , , ), , const char[4] , , , . const , , const .

const UB, constness . , , - const, - . const , const, , , , , const, , , const-casting, , , , const, , , , .

, ++ const ( volatile), , , (, volatile, ) const / volatile, , , , const / volatile. , , , , , ; , volatile ( ), . .

+2

Undefined undefined. , .

, , . , , , . , , , . .

, , , . , .

:

class BaseClass {};
class Derived : public BaseClass {};

BaseClass *pDerived = new Derived();
BaseClass *pBase = new Base();

Derived *pLegal = static_cast<Derived*>(pDerived);
Derived *pIllegal = static_cast<Derived*>(pBase);

++ , . undefined. , ++ "undefined"? .

, ++ , pBase Derived , pBase Derived*. Derived, undefined.

no-op; . - . ; , . no-op, .

, "", undefined . , , . , . . , , - .

const cast. const , const, , . , , .

+1

, const- , , , , - , , const, , . non-const const , , , . , const: , .

Undefined , , , .

0
source

All Articles