masoud
masoud

Reputation: 56479

Optimization in std::string based on same const literals

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?

Upvotes: 2

Views: 593

Answers (2)

Thomas Wiegert
Thomas Wiegert

Reputation: 1

One reason for this behaviour might be the memory management of the objects:

The std::string objects are responsible for their character arrays. That implies that the arrays are deleted in the std::string destructor - and such an array should only be deleted once.

In C char arrays declared as

const char* bla = "blabla";

are - or should never be - freed.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476950

The C++ standard library classes by and large all implement strong value semantics, which means that each object owns all its data, and so the lifetime of the object is easy to reason about. While a reference-tracking implementation might be possible, it would come at a considerable complexity cost, and that doesn't fit the "don't pay for what you didn't ask for" philosophy of C++.

There have long been discussions about non-owning string-like classes (something like string_ref and array_ref, if you want to search for it), which would only be views on existing strings. This would put the burden on the user to ensure that the lifetime of the underlying shared data fits the application. It might become part of the standard in the future, but search around for existing implementations if you're interested.

Upvotes: 5

Related Questions