Is it undefined behavior if const member function changes *this through its argument?
Does this code exhibit undefined behavior or is the behavior well-defined? The const member function promises that it will not change *this, but it actually changes *this through the argument. Can it output 1? #include <iostream> class A { public: A(int n) : n_(n) {} void DoubleTo(A& a) const { a.n_ = 2 * n_; std::cout << n_ << "\n"; } private: int n_ = 0; }; int main() { A a(1); a.DoubleTo(a); } Gemini has told me that a correct compiler should take a potential aliasing a and *this into account, and should not keep the value of n_ in a register after the assignment, changing a: it is required
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.