Chris said:
red said:
Colander wrote:
Static say something about scoop. (There is only one)
Const says something about value. (You can't[really shouldn't] change
it)
They are different concepts.
In the case under discussion (local static), your first statement is
incorrect.
static in this case says something about *LIFETIME*. The variable is
constructed exactly once and destroyed only at the end of program execution.
It has nothing to do with scope in this case, and further, you
explanation (There is only one) has nothing to do with scope either.
I guess my question is--does declaring a local const string that is
initialized to a literal value as static have any real practical
purpose?
Yes.
I understand that static means "create once", but aren't
string literals like this created and stored somewhere "once" by the
compiler anyway?
No. You are confusing a std::string with an array of const char
(a.k.a. a "C-string" or "string literal"). The latter should only be
created once (or at least typically is, whether or not that is required
by the Standard). A std::string that was _not_ static, on the other
hand, should be constructed each time the function is entered, and
destroyed each time the function is exited. Every Single Time. It is
possible that a good optimizer might optimize that construction and
destruction away, given that the std::string is decleared const, but in
practice few if any do.
In sum: I think your confusion arises from the fact that the
std::string is initialized with a string literal. That string literal
may well be created only once, but the std::string will be constructed
and destructed multiple times. And that means that putting in "static"
does have a practical purpose. Whether that purpose - saving all those
gratuitous constructions and destructions - matters here could only be
determined by profiling the code.
Best regards,
Tom