The function test()
is returning a reference (not a copy) to the static variable test2
. The static keyword makes the function test
maintain the value of variable test2
between calls. Hence when you call test()
it returns the reference allowing you to change the value of test2
inside the test()
. This results in wcerr << test2 << endl;
printing out "Then!"
Note the static keyword has different meaning depending on the context. Making the function static makes the the function only visible to other functions in the file. If you put a static function in a header you will have deceleration for that function for each #include of that header.
What you probably wanted to say is
#include <iostream>
#include <string>
using namespace std;
wstring & test() {
static wstring test2;
return test2;
}
int main()
{
test() = L"Then!";
wcerr << test() << endl;
}