The code below compiles on Linux (g++ 4.8.4) and Windows (VS Express 2013) but produces different results when executed.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string str = str;
cout << "'str.length()': "
<< str.length() << endl;
return 0;
}
On Linux I get:
'str.length()': 140187593065792
On Windows I get:
'str.length()': 0
In addition, if I change the initialization statement as shown below then it complies but it crashes at runtime (On Linux I get: terminate called after throwing an instance of 'std::bad_alloc'):
string str = str + str;
I understand that, in both cases, this is not the usual way one would initialize a string variable. However, could someone please explain what is really wrong with this code? Also, why the output is different in the first case?