Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why don't const l-value references to r-values result in dangling references?

Why is the following not an error?

const auto& foo = std::string("foo");

In my mental model of C++ I think of references as glorified non-null pointers that the language wraps in syntactic sugar for me. However the code below would be an error but the above is not.

const auto* foo = &(std::string("foo"));

In the reference case why is the string not immediately destructed after the r-value expression is evaluated?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because this is the language rule Lifetime of a temporary

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference.

There is no such rule for const pointers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading