C++函数返回对数组的引用

Jae*_*ege 11 c++ c++11

除了使用指针之外,还有其他方法可以从函数返回接收对数组的引用吗?

这是我的代码.

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;
}
Run Code Online (Sandbox Code Playgroud)

和一个类版本.

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;
}
Run Code Online (Sandbox Code Playgroud)

注意:const代码中省略了限定符.

我知道数组的名称是指向该数组中第一个元素的指针,因此使用指针接收是完全可行的.

对不起,我搞错了.从Array到指针衰减

存在从数组类型的左值和右值到指针类型的右值的隐式转换:它构造指向数组的第一个元素的指针.

请忽略那个XD

我只是对我在开始时提出的问题感到好奇:)

jua*_*nza 13

除了使用指针之外,还有其他方法可以从函数返回接收对数组的引用吗?

是的,使用对数组的引用,与任何其他类型一样:

int (&ref)[3] = a.foo();
Run Code Online (Sandbox Code Playgroud)

为了避免使用笨重的语法,您可以使用typedef替代语法.

typedef int int_array3[3];

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

...

int_array3& ref = a.foo();
Run Code Online (Sandbox Code Playgroud)

  • `auto& ref = a.foo();` 也是可能的 (3认同)

Sla*_*ica 11

您应该使用std :: array来避免混淆,并使代码更清晰,更安全,更少笨重:

class A {
public:
    typedef std::array<int,3> 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;
}
Run Code Online (Sandbox Code Playgroud)

我知道数组的名称是指向该数组中第一个元素的指针

这是不正确的,数组可以隐式转换为指向第一个元素的指针.它不一样.

  • 这很容易引起误解,因为它给人的印象是无法返回对数组的引用,或者无法使用返回值。 (2认同)
  • @juanchopanza我在哪说? (2认同)
  • 我不是说你说的.只是通过专注于`std :: array`解决方案,而没有提到它是完美的返回并使用对数组的引用,这给人的印象是你不能这样做. (2认同)
  • 返回对数组的引用并不完美,因为这会导致糟糕且难以理解的代码.这首先是C++,正如你在答案中提到的那样,C数组很笨重 (2认同)
  • @Slava,没问题...我可能还建议您向 ISO C++ 委员会发送一份提案,以消除对本机数组的引用。如果您足够快,您的提案可能会成为 C++20 的一部分。 (2认同)