Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined behavior with const_cast? [duplicate]

Tags:

c++

const-cast

What is happening here?

const int a = 0;
const int *pa = &a;

int *p = const_cast<int*>(pa);
*p = 1;  // undefined behavior ??
cout << a << *p;  // ??

My compiler outputs 0 and 1, but address of 'a' and value of 'p' is the same, so I'm confused how is this possible.

like image 931
Tracer Avatar asked Aug 08 '14 18:08

Tracer


People also ask

Is const_cast undefined behavior?

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.

What is true for const_cast?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

How is it possible to have both const and non-const version of a function?

There are legitimate uses of having two member functions with the same name with one const and the other not, such as the begin and end iterator functions, which return non-const iterators on non-const objects, and const iterators on const objects, but if it's casting from const to do something, it smells like fish.

Can you call a non-const function from a const function?

When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects. For example, the following program has compiler errors.


2 Answers

Quote from cppreference:

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

So yes, modifying constant variables is undefined behavior. The output you see is caused by the fact that you tell the compiler that the value of a will never change, so it can just put a literal 0 instead of the variable a in the cout line.

like image 96
Baum mit Augen Avatar answered Oct 02 '22 01:10

Baum mit Augen


§7.1.6.1 [dcl.type.cv]/p4:

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.

like image 37
T.C. Avatar answered Oct 02 '22 01:10

T.C.