Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type-deduction for arrays prioritizes pointer to first over reference to array?

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...)

like image 556
pepper_chico Avatar asked Jan 07 '14 21:01

pepper_chico


2 Answers

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&&.

like image 85
Yakk - Adam Nevraumont Avatar answered Sep 29 '22 05:09

Yakk - Adam Nevraumont


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);
}
like image 22
Angew is no longer proud of SO Avatar answered Sep 29 '22 06:09

Angew is no longer proud of SO