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

标签 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;
}

还有一个类版本。

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

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

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

对不起,我弄错了。来自 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.

请无视XD

我只是对我一开始问的问​​题感到好奇:)

最佳答案

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

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

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

为避免笨拙的语法,您可以改用 typedef

typedef int int_array3[3];

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

...

int_array3& ref = a.foo();

关于C++ 函数返回对数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439284/

相关文章:

c++ - 其他线程是否总是以相同的顺序看到不同线程中对同一位置的两次轻松写入?

c++ - 检查可变参数模板声明中的参数类型

c++ - PPL Combinable 的 SIMD 对齐问题

c++ - C 是否对声明的变量大小有 64k 的限制?

C++11 move 语义和 Microsoft Visual C++ 编译优化

c++ - c++11 中 3 个线程和 2 个共享资源的同步问题

c++ - 你能解释一下 bool 如何控制循环吗?

c# - 使用 DirectX 防止屏幕捕获

c++ - vector::size() 如何在常数时间内返回 vector 的大小?

c++ - GCC constexpr 允许添加,但不允许使用地址进行按位或