Is there any other way to receive a reference to an array from function returning except using a pointer?
Here is my code.
int ia[] = {1, 2, 3};
decltype(ia) &foo() { // or, int (&foo())[3]
return ia;
}
int main() {
int *ip1 = foo(); // ok, and visit array by ip1[0] or *(ip1 + 0)
auto ip2 = foo(); // ok, the type of ip2 is int *
int ar[] = foo(); // error
int ar[3] = foo(); // error
return 0;
}
And a class version.
class A {
public:
A() : ia{1, 2, 3} {}
int (&foo())[3]{ return ia; }
private:
int ia[3];
};
int main() {
A a;
auto i1 = a.foo(); // ok, type of i1 is int *, and visit array by i1[0]
int i2[3] = a.foo(); // error
return 0;
}
Note: const
qualifier is omitted in code.
I know the name of the array is a pointer to the first element in that array, so using a pointer to receive is totally viable.
Sorry, I made a mistake. From Array to pointer decay
There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array.
Please ignore that XD
I'm just curious about the question I asked at the beginning :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…