How to call a non-const function within a const function (C++)
int Random() const { return var_ ? const_cast<ClassType*>(this)->newCall(4) : 0; } But it’s not a good idea. Avoid if it’s possible!
int Random() const { return var_ ? const_cast<ClassType*>(this)->newCall(4) : 0; } But it’s not a good idea. Avoid if it’s possible!
You truly want immutable objects of some type plus value semantics (as you care about runtime performance and want to avoid the heap). Just define a struct with all data members public. struct Immutable { const std::string str; const int i; }; You can instantiate and copy them, read data members, but that’s about it. … Read more
it is pretty much designed to be only used with legacy APIs that are not const correct i.e. with a function you can’t change that has non const interface but doesn’t actually mutate anything on the interface
You are not allowed to const_cast and then modify 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 … Read more
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