Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

c++ - Non-const reference may only be bound to an lvalue

Could someone please explain how to simulate this error? and also what this complains about.

"A non-const reference may only be bound to an lvalue" in C++

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An lvalue is, roughly, whatever may be on the left side of an assignment statement. References provide aliases for other objects:

std::string s;
std::string & rs = s;  // a non-const reference to s
std::string const & crs = s; // a const reference to s

Given the above definitions, referring to rs or crs is the same as referring to s, except that you cannot modify the referred string through crs, as it is const. A variable is an lvalue, so you are allowed to bind a non const reference to it. In contrast you can bind const references to temporary values as in:

std::string const & crs1 = std::string();

However the following is illegal:

std::string & rs1 = std::string();

This is because using non-const references you imply that you want to modify the referenced object. However temporaries bound to references are destroyed when the reference go out of scope. As it is not always intuitive when C++ creates temporary objects, binding them to non-const references has been disallowed, to avoid you the unpleasant surprise of changing your object as you like, just to see it destroyed a few statements later.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...