int v[1];
auto p1 = v;
auto &p2 = v;
auto *p3 = v;
p1
is of type int *
(same for p3
). Particularly at this trivial sample I find p2
( int (&)[1]
) more useful since it inherents array semantics, e.g. I can apply sizeof
on p2
to give the same as sizeof
on v
.
Is there a standard quotation regarding that?
Why defaulting to references is a bad idea? (for this arrays case I mean, almost no c++ programmer cares about them these days anyway...)
auto
deduces a non-reference type.
auto&
deduces a reference.
auto const&
deduces a const
reference.
auto&&
deduces either a reference, a const
reference, or an rvalue reference.
This works just like how type deduction when calling a template
function works.
template<typename T>
void foo( T t );
T
will never be deduced by be a reference type -- it will always be a value type when deduced.
auto
follows almost identical rules:
template<typename T>
void foo( T&& t );
is the reasonably well known "universal reference", analogous to a variable of type auto&&
.
I believe it's for consistency with non-template functions. Arrays undergo the array-to-pointer conversion anytime they're accessed, except when being bound to a reference. So with the existing rules, the following are consistent:
int v[1];
void foo(int *);
int main()
{
foo(v);
}
and
int v[1];
template <class T>
void foo(T);
int main()
{
foo(v);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With