Passing an integer to a function requesting a link

Why is this code well formed? I do not pass a link to the function:

void function(const int& ref) { } int main() { function(1); } 
+7
c ++
source share
2 answers

The compiler can create a temporary one from a constant, and temporary resources are allowed to link const links. If the link was not const, this will not be allowed.

+2
source share

References to lvalue constants can bind to rvalues. Rvalues, like your literal 1 , do not have a constant alias, so if you need to modify it, you will not be able to observe the effect, but if you promise not to change it (namely, by accessing it through a permalink), you can still to have completely reasonable code and why this binding is allowed.

(You can also associate rvalues ​​with (mutable) rvalue references: void function(int &&) In this case, the rvalue reference becomes the (unique) value alias.)

Note also that without this rule, it would be impossible to initialize variables from functions returning prvalues, or to use copy initialization in general:

 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 
+6
source share

All Articles