Practice mode C++

Is the declaration const int& r = 5; valid in C++?

Correct answer B. Yes; a temporary is created and its lifetime is extended to match r

Explanation

A non-const lvalue reference (int&) cannot bind to a literal, but a reference to const can. The compiler materialises a temporary int holding 5 and binds r to it, and binding a reference directly to a temporary extends the temporary's lifetime to that of the reference. This is why functions taking const T& accept literals and other temporaries.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.