Posts

Showing posts with the label storage

Is storage for the same content string literals guaranteed to be the same?

Is the code below safe? It might be tempting to write code akin to this: #include <map> const std::map<const char*, int> m = { {"text1", 1}, {"text2", 2} }; int main () { volatile const auto a = m.at("text1"); return 0; } The map is intended to be used with string literals only. I think it's perfectly legal and seems to be working, however I never saw a guarantee that the pointer for the literal used in two different places to be the same. I couldn't manage to make compiler generate two separate pointers for literals with the same content, so I started to wonder how firm the assumption is. I am only interested whether the literals with same content can have different pointers. Or more formally, can the code above except? I know that there's a way to write code to be sure it works, and I think above approach is dangerous because compiler could decide to assign two different storages for the literal, especially if they...