Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this const_cast undefined behavior?

Tags:

c++

const-cast

I was wondering whether the following is undefined behavior

// Case 1:
int *p = 0;
int const *q = *const_cast<int const* const*>(&p);

// Case 2: (I think this is the same)
int *p = 0;
int const *const *pp = &p;
int const *q = *pp;

Is this undefined behavior by reading a int* as if it were a int const*? I think it is undefined behavior, but I previously thought that only adding const in general is safe, so I'm unsure.

like image 519
Johannes Schaub - litb Avatar asked May 11 '11 19:05

Johannes Schaub - litb


People also ask

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.

Is const_cast safe?

const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and you pass in a modifiable char * , it's safe to const_cast that parameter back to a char * and modify it.


1 Answers

Qualification-wise, it's fine. With each expression split into a statement:

int *p = 0; // ok
int **addrp = &p; // ok
int const *const *caddrq = addrp; // ok, qualification conv. according to §4.4/4
int const *q = *caddrq; // ok

Note that the rules of const_cast (§5.2.11/3) are identical to those of qualification conversion, but without the requirement of being monotonically increasing in qualification. In your case, because you're only ever adding qualifications the const_cast is unnecessary.


Concerning aliasing, I don't think it's an issue, here, or at least it's not intended to be.

Like you mentioned, there's a new bullet in the C++0x list of allowed access methods (§3.10) that allows similar types ("similar" being types arising from qualification conversions). In C++03 that bullet is missing, but I suspect that the bullet about allowing more cv-qualified access was meant to cover that, but it technically isn't so (that is, the commitee overlooked this).

like image 132
GManNickG Avatar answered Oct 03 '22 16:10

GManNickG