-3

I have this small c++ code snippet, may someone explain how the operator= works here ?

#include <iostream>
#include <string>

    using namespace std;

    static wstring & test() {
        static wstring test2;
        return test2;
   };


   int main()
   {
       test() = L"Then!";
       wcerr << test() << endl;
   }
UnoSolo
  • 75
  • 2
  • 8

2 Answers2

1

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;
}
ZNackasha
  • 755
  • 2
  • 9
  • 29
0

The function test() returns a reference to the static variable test2. A reference refers to a variable; you could substitute the variable in place of the reference.

This is equivalent to the code:

static wstring test2;
int main()
{
    test2 = L"Then!";
    wcerr << test2 << endl;
}

Search your favorite C++ reference for "references".

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • On the VC++ compiler, the '=' is definited as std::wstring::operator=(const wchar_t *_Ptr) so is overloaded. What I don't understand is how work the assignment, test() = L"Then!";. test() is a function, how is possible to set the static wstring inside the function ? – UnoSolo Jun 29 '19 at 17:35
  • @UnoSolo Do you know what a [reference](https://en.cppreference.com/w/cpp/language/reference) is in C++? – Blastfurnace Jun 29 '19 at 17:42
  • @UnoSolo it returns a reference to a `wstring`, so the assignment is performed on the object the reference refers to (i.e. the `wstring`) – Cruz Jean Jun 29 '19 at 17:45
  • It'd be interesting to hear the reasoning behind the downvote. – Ted Lyngmo Jun 29 '19 at 18:53