Does cast away const of *this cause undefined behavior?
问题 The following code compiles. It seems to run fine. But would it cause any undefined behavior? I want to cast away the const of *this . This is for allowing a const my_iterator to mutate the data it points at. Test: class A { public: A(const int x) : x_(x) {} void set_x(int x) { x_ = x; } void set_x2(const int x) const { const_cast<A&>(*this).set_x(x); } int x_; }; int main() { A a(10); a.set_x2(100); } 回答1: Your example is not undefined behavior because a is not const . However, if a were