Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

c++11 - C++ function returning reference to array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is there any other way to receive a reference to an array from function returning except using a pointer?

Yes, using a reference to an array, like with any other type:

int (&ref)[3] = a.foo();

To avoid the clunky syntax, you could use a typedef instead.

typedef int int_array3[3];

...
int_array3& foo() { return ia; }

...

int_array3& ref = a.foo();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...