Const references to literals

This is the code snippet that I found in the book C++ Primer, 5th Edition:

const int &ri = 42;


As far as I know, I am now binding a reference to an integer literal.
How and why is the code snippet valid? Can anybody tell me that?

(By the way, my thanks to JLBorges there. I forgot to mention that I am a newbie.)
Last edited on
You are binding a reference to const to a temporary object of type int.
The life-time of that anonymous temporary object is extended to match the life time of the reference.

There are a few exceptions to this rule; see 'Lifetime of a temporary' here:
https://en.cppreference.com/w/cpp/language/reference_initialization
Topic archived. No new replies allowed.