const char* str ="Hello World!"
str = "HELLO!"
In this code, will the string "Hello World!" be erased from memory or will it be left alone?
This is not specified by the C++ standard. Your compiler can do whatever it wishes here, including not even storing the original string in the first place, and effectively compiling the following code only:
const char* str = "HELLO!"
Your compiler can prove that performing this optimization has no observable effects, and the C++ standard allows C++ compilers to implement any optimization that has no observable effects.
So what happens here depends entirely on your C++ compiler.
In general, string constants tend to be in the global data section, and aren't "freed" until the program ends.
You can see this here: https://godbolt.org/z/a3TbjTba1
String literals, according to [lex.string]/14
are:
Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above
str
is a pointer toconst char
, so can be reassigned (butstr
cannot be used to change the data thatstr
points at - e.g. it cannot be used to overwrite a string literal). – Peter