safe to assume multiple instances of same stirng have same address?

This topic is 4839 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Would it be safe to assume that multiple instances of constant strings will always always have the same address in memory? Like take this for example:
void f()
{
std::cout<< (int)"hap656456546py"<< std::endl;
std::cout<< (int)"gipp"<< std::endl;
std::cout<< (int)"happy"<< std::endl;
std::cout<< (int)"gipp"<< std::endl;
std::cout<< (int)"happy"<< std::endl;
std::cout<< (int)"hap656456546py"<< std::endl;
}

int main()
{
f();
std::cout<< std::endl;
std::cout<< (int)"hap656456546py"<< std::endl;
std::cout<< (int)"gipp"<< std::endl;
std::cout<< (int)"happy"<< std::endl;
std::cout<< (int)"gipp"<< std::endl;
std::cout<< (int)"happy"<< std::endl;
std::cout<< (int)"hap656456546py"<< std::endl;
std::cout<< std::endl;
f();
}


This confirms my assumption a bit, but I need to know if this is the "standard" beahvior and it will always work. Thanks.

Share on other sites
No, this is purely a compiler optimization. I would assume at least a few compilers wouldn't do it if the optimizations were turned off.

Share on other sites
Quote:
 Original post by IFooBarWould it be safe to assume...

As hh10k said, this is a compiler optimization. Some compilers may have flags to support this, which should allow safe assumption of this WITHIN THE SAME TRANSLATION UNIT (read: object file). But as a "general" rule it is not a safe assumption.

I see...

Thanks.

Share on other sites
You can make that more likely in MSVC.NET by changing the following option:

Project properties ->
Configuration Properties ->
C/C++ ->
Code Generation ->
Enable String Pooling = Yes

However, as mentioned above, relying on specific compiler behaviour for things like this should be considered extremely bad (and dangerous) practice.

If you need shared strings at a specific address, then do it explicitly.