Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an integer to a function asking for reference

Tags:

c++

Why is this code well-formed? I'm not passing a reference to the function:

void function(const int& ref) {

}

int main()
{
    function(1);
}
like image 672
Dean Avatar asked Oct 16 '14 21:10

Dean


2 Answers

Constant lvalue references can bind to rvalues. Rvalues, like your literal 1, don't have a persistent alias, so if you were to modifying it, you wouldn't be able to observe the effect, but if you promise not to modify it (namely by accessing it through a constant reference), you can still have perfectly sensible code, and that's why this binding is allowed.

(You can also bind rvalues to (mutable) rvalue references: void function(int &&) In that case, the rvalue reference becomes the (unique) alias of the value.)

Note also that without this rule it would be impossible to initialize variables from functions that return prvalues, or use copy-initialization at all:

struct T { T(int); };

T f();

T x = 1;     // ===  "T x = T(1);", copy constructor wants to bind to prvalue
T x = f();   // ditto
T x((f()));  // ditto
like image 50
Kerrek SB Avatar answered Nov 03 '22 03:11

Kerrek SB


The compiler can create a temporary from the constant and temporaries are allowed to bind to const references. If the reference wasn't const, this wouldn't be allowed.

like image 37
David Schwartz Avatar answered Nov 03 '22 03:11

David Schwartz