0

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?

2
  • 1
    You used a weird quote mark in the g call .. it should be " Commented Nov 11, 2016 at 2:12
  • In short, lvalue reference can't be bound to temporary. Commented Nov 11, 2016 at 2:12

1 Answer 1

3

That's because the language rules are designed this way. You can bind an rvalue to a const lvalue reference (and extend its lifetime to that of the reference), because it is explicitly allowed.

Assuming C++03 since you're using g++ 4.1.2

§ 8.5.3 [dcl.init.ref] / 5

A reference to type “cv1T1” is initialized by an expression of type “cv2T2” as follows:

  • If the initializer expression
    • is an lvalue (but is not a bit-field), and “cv1T1” is reference-compatible with “cv2T2,” or
    • has a class type (i.e.,T2is a class type) and can be implicitly converted to an lvalue of type [...]
  • Otherwise, the reference shall be to a non-volatile const type [...]
    • If the initializer expression is an rvalue, withT2a class type, and “cv1T1” is reference-compatible with “cv2T2,” [...]
    • Otherwise, a temporary of type “cv1T1” is created and initialized from the initializer expression using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.