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 are placed in different translation units. Am I right?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…