How to return an array from a function?

后端 未结 5 688
说谎
说谎 2020-11-22 13:11

How can I return an array from a method, and how must I declare it?

int[] test(void); // ??
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 13:42

    It is not possible to return an array from a C++ function. 8.3.5[dcl.fct]/6:

    Functions shall not have a return type of type array or function[...]

    Most commonly chosen alternatives are to return a value of class type where that class contains an array, e.g.

    struct ArrayHolder
    {
        int array[10];
    };
    
    ArrayHolder test();
    

    Or to return a pointer to the first element of a statically or dynamically allocated array, the documentation must indicate to the user whether he needs to (and if so how he should) deallocate the array that the returned pointer points to.

    E.g.

    int* test2()
    {
        return new int[10];
    }
    
    int* test3()
    {
        static int array[10];
        return array;
    }
    

    While it is possible to return a reference or a pointer to an array, it's exceedingly rare as it is a more complex syntax with no practical advantage over any of the above methods.

    int (&test4())[10]
    {
            static int array[10];
            return array;
    }
    
    int (*test5())[10]
    {
            static int array[10];
            return &array;
    }
    

提交回复
热议问题