In C++ it is possible to pass an rvalue to a function accepting a const lvalue reference. I don't understand why this is.
The expression Function(Entity())
is ostensibly an rvalue, it has no identifiable location in memory. If Function()
were to take an Entity&
rather than a const Entity&
, then this would not work. But if the function takes a const lvalue reference rather than an lvalue reference, then this works fine.
Could someone please provide an explanation for how this works and why?
class Entity
{
Entity()
{
std::cout << "Entity created\n";
}
}
void Function(const Entity& e) // recieved as const lvalue reference
{
std::cout "Inside function\n";
}
int main()
{
Function(Entity()); // passing rvalue
}