Lifetime of a string literal returned by a function

Solution 1:

The C++ Standard does not say where string literals should be stored. It does however guarantee that their lifetime is the lifetime of the program. Your code is therefore valid.

Solution 2:

The "Some text!!" does not have a scope. Scope is a property of a named entity. More precisely, it is a property of the name itself. "Some text!!" is a nameless object - a string literal. It has no name, and therefore any discussions about its "scope" make no sense whatsoever. It has no scope.

What you seem to be asking about is not scope. It is lifetime or storage duration of "Some text!!". String literals in C/C++ have static storage duration, meaning that they live "forever", i.e. as long as the program runs. So, the memory occupied by "Some text!!" is never released.

Just keep in mind (as a side note) that string literals are non-modifyable objects. It is illegal to write into that memory.

Solution 3:

String will be stored statically in special (usually read-only on modern OS) section of the program binary. Its memory is not allocated (individually for the string, only for total section while loading it to memory) and will not be deallocated.