C++ function returning reference to array

后端 未结 5 1297
天命终不由人
天命终不由人 2021-01-04 08:47

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};
decl         


        
5条回答
  •  耶瑟儿~
    2021-01-04 09:04

    You should use std::array to avoid confusion and make cleaner, safer and less clunky code:

    class A {
    public:
        typedef std::array array;
        A() : ia{1, 2, 3} {}
        array &foo(){ return ia; }
    private:
        array ia;
    };
    
    int main() {
        A a;
        auto i1 = a.foo();      // ok, type of i1 is A::array, it is a copy and visit array by i1[0]
        for ( int i : i1 ) {}   // you can iterate now, with C array you cannot anymore
        auto &i2 = a.foo();     // ok, type of i2 is A::array&, you can change original by i2[0] = 123 
        A::array i3 = a.foo();  // fine, i3 is now a copy and visit array by i3[0]
        A::array &i4 = a.foo(); // fine, you can change original by i4[0] = 123
        int *i5 = a.foo().data();  // if you want old way to pass to c function for example, it is safer you explicitly show your intention
        return 0;
    }
    

    I know the name of the array is a pointer to the first element in that array

    This is incorrect, array can be implicitly converted to a pointer to the first element. It is not the same.

提交回复
热议问题