We know compilers can reuse identical constant string literal to save memory efficiently. This optimization is optional for compilers.
Two string literals have the same pointer value?
const char *s1 = "HELLO";
const char *s2 = "HELLO";
s1
and s2
can have same address. They have the same address in many compilers. For example, both are pointing to the address 0x409044
.
Well.
The question in my mind is, why std::string
dosen't try to has same advantage? And it doesn't try to just wrap std::string
around that address.
const std::string ss1("HELLO");
const std::string ss2("HELLO");
cout << (void*) ss1.c_str() << endl;
cout << (void*) ss2.c_str() << endl;
ss1
and ss2
have two distinct addresses.
Is it technically impossible? Prohibited by the language? Or the developers of implementations of the standard library just don't want it?