I am using g++4.1.2 to compile this:
cat 1.cpp #include<iostream> #include<string> using namespace std; void f(const string& s){} void g(string& s){} void h(string s){} int main() { string s="abc"; f("abc"); g("abc”);//Error h("abc"); return 0; } It failed at line “g();”
$ g++ 1.cpp 1.cpp: In function ‘int main()’: 1.cpp:11: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’ 1.cpp:5: error: in passing argument 1 of ‘void g(std::string&)’ I don’t quite understand that, as long as “abc” could be the constructor parameter for std::string:
For f(),"abc" can be used to construct a string(const char*), as a const reference to string
For h() “abc” can be used to construct a r-value, temporary std::string object.
For g(),why it cannot be used to construct a left-value reference string&, while const reference string& is OK?
gcall .. it should be"