I know that in C/C++, if you write a string literal, this is actually placed into read-only memory with static (lifetime of the program) storage. So, for example:
void foo(const char* string) {
std::cout << static_cast<void const*>(string) << std::endl;
}
int main() {
foo("Hello World");
}
should print out a pointer to someplace in read-only memory.
Here's my question, let's say I want to write a copy-on-write String class which has an optimization for static data like this. Instead of copying the whole string into dynamically-allocated memory (which is expensive), why not just keep a pointer to the static data instead. Then, if a write actually does need to occur, then I can make a copy at that point.
But how can I tell if a string is static or something like:
int main() {
char[] myString = "Hello World";
foo(myString);
}
In this case, myString is located in the stack and not the heap, thus it's lifetime is not static.
My first thought was a special constructor for std::string_view, but I'm not sure that std::string_view implies a string with static lifetime either...