cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
General C++ Programming
Const references to literals
Const references to literals
Aug 22, 2018 at 8:19am UTC
Jeffrey10th
(1)
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
Aug 22, 2018 at 8:42am UTC
Aug 22, 2018 at 8:40am UTC
JLBorges
(13770)
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.