can memcpy() be used to change “const” member data?

前端 未结 2 1175
感情败类
感情败类 2021-01-13 11:44

For a struct with const members

struct point { const int x; const int y; };

that is used as member data



        
2条回答
  •  独厮守ぢ
    2021-01-13 12:16

    This is clearly undefined behavior. Now, "can" this be done? Sure, it can, but only in the sense that the compiler will not complain. But one aspect of C++ is just because the compiler doesn't complain it doesn't mean that the resulting code will work right.

    It's only a matter of time before someone writes some code that reads pt, calls move_x(), and then reads pt again.

    A modern, optimizing compiler will rightfully assume that because the code is reading const instances, their values cannot change, and then proceed and optimize away the second read from pt, using the data cached from the first read of pt, in the CPU registers.

    And then, the hapless programmer will spend a week trying to figure out why the code is clearly not doing what the program says it should be doing.

提交回复
热议问题