Same strings in array have same memory address

梦想的初衷 提交于 2019-11-29 11:34:49

It is called constant merging. It is enabled at higher levels of optimization, typically. The compiler simply takes all of the unique constant values and crunches them down. Good for memory usage and cache efficiency.

gcc has -fmerge-constants or using -O and company

Other compilers may or may not do it. It is compiler specific.

Since it is about the easiest optimization operation to implement I would imagine all C++ compilers do it.

This is a perfect example of why:

  1. You can't make assumptions about where a constant value will live (undefined behavior)
  2. You shouldn't make changes to constant values (undefined behavior)

but we see many questions about people (not yourself) observing they got away with modifying a constant string after casting away const.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!