Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++11 - Binding a const reference to a literal in C++


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

1 Answer

0 votes
by (71.8m points)
  1. Why in the 1st example a plain reference cannot be bind to a literal and this example fails.

Because the rules of the language say that reference to non-const cannot bind to an rvalue. And a literal is a prvalue.

  1. How does the second example works?

A temporary object is materialised from the prvalue, the reference is bound to that temporary object and the lifetime of the temporary is extended to match the lifetime of the reference.

  1. i want to create a variable using int i=0; instead can i create it using const auto &i=0 ?

Note that you couldn't modify the temporary object through the const reference, while you can modify int. As such, these aren't quite the same. Also, as a member variable or a parameter, these would differ significantly.

In some cases you could, but you shouldn't because it's unnecessarily complicated. Remember that you were confused about the code. You wont be the last. Prefer writing programs that don't confuse others. If you want to create a variable using int i=0;, then use int i=0;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...