Reputation: 257
I have a method with a parameter that is read-only.
template <typename T>
void foo(const T t) {...}
This definition has the benefit that foo(2)
is syntactically correct. However, it has the downside that applying foo
on a big object makes it copy the object. Since I only read from the argument, this is just a waste of time and memory.
The standard solution is to make the parameter t
a const reference. However, this has the downside that foo(2)
is not syntactically correct anymore. I would have to do int i = 2; foo(i);
which I find unfortunate.
Is there a way to get the best of both worlds? So such that foo(2)
is syntactically correct and applying foo
on an object makes it pass by reference?
EDIT: Apparently a const reference is already the best of both worlds. Now I would like to know why this is. Why is foo(2)
syntactically correct? How can 2
become a reference here?
Upvotes: 1
Views: 208
Reputation: 275405
C++ will materialize temporaries when needed, and you can bind a temporary to a const&
, but not a &
.
So foo_value(2)
creates an int
with value 2
called t
as a parameter. foo_cref(2)
creates an anonymous temporary, then binds the int const& t
parameter to it, where foo_value
and foo_cref
are the obvious variants of foo
you talk about in the question.
Upvotes: 1