I have the following code:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string &s1 = argv[0]; // error
const string &s2 = argv[0]; // ok
argv[0] = "abc";
cout << argv[0] << endl; // prints "abc"
cout << s2 << endl; // prints program name
}
I receive the following error for s1
:
invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'char*'
Then why does the compiler accept s2
?
Interestingly, when I assign a new value to argv[0]
then s2
does not change. Does the compiler ignore that it's a reference and copies the value anyway? Why does it happen?
I write this in Code::Blocks 16.01 (mingw). The same happens with/without -std=c++11
.