How to convert “pointer to pointer type” to const?

The language allows implicit conversion from double ** to const double *const *, but not to const double **. The conversion you attempt would implicitly violate the rules of const correctness, even though it is not immediately obvious. The example in the [de-facto standard] C++ FAQ illustrates the issue https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion Basically, the rule is: once … Read more

Is it allowed to cast away const on a const-defined object as long as it is not actually modified?

Yes. This is entirely legal. (It is dangerous, but it is legal.) If you (attempt to) modify a an object declared const, then the behaviour is undefined. From n4659 (which is the last draft of C++17), section 10.1.7.1 [dcl.type.cv] para 4: Except that any class member declared mutable (10.1.1) can be modified, any attempt to … Read more

Is this undefined behavior with const_cast? [duplicate]

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 … Read more

How to use const_cast?

You are not allowed to const_cast variables that are actually const. This results in undefined behavior. const_cast is used to remove the const-ness from references and pointers that ultimately refer to something that is not const. So, this is allowed: int i = 0; const int& ref = i; const int* ptr = &i; const_cast<int&>(ref) … Read more

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. However, if the original … Read more