Idiomatic way to create an immutable and efficient class in C++

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

How to use const_cast?

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

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