【问题标题】:Trailing return type array尾随返回类型数组
【发布时间】:2015-09-10 00:00:03
【问题描述】:
auto function(int i) -> int(*)[10]{

}

谁能帮助我如何使用尾随返回类型返回指向 10 个整数数组的指针?任何示例都会有所帮助。

【问题讨论】:

  • 你在这篇文章中没有做到这一点吗?
  • 我不知道 return 在函数体内是如何工作的。对结构有点困惑。
  • 如果您想要一个指向 T 的指针,请创建一个 T 并获取其地址...或获取 nullptr 并将其转换为 T*

标签: c++ arrays types return trailing


【解决方案1】:

如果您不关心您的返回值是否可取消引用(并且您没有指定),以下将“返回指向 10 个整数数组的指针”:

auto function(int i) -> int(*)[10]
{
    return nullptr;
}

【讨论】:

  • 如何将 i 分配给所有 10 个整数值并返回数组值并在主函数中打印?
【解决方案2】:

首先,您需要确定整数的存储位置、如何“共享”它们以及调用者或被调用者是否对其生命周期负责。

选项包括...

1) 返回一个指向新动态分配的内存的指针:

auto function(int i) -> int(*)[10] {
    int* p = new int[10];
    p[0] = 1;
    p[1] = 39;
    ...
    p[9] = -3;
    return (int(*)[10])p;
}

// BTW it's usually cleaner (avoiding the ugly cast above) to handle
// arrays via a pointer (but you do lose the compile-time knowledge of
// array extent, which can be used e.g. by templates)
int* function(int i) {
    int* p = ...new and assign as above...
    return p;
}

// either way - the caller has to do the same thing...

void caller()
{
    int (*p)[10] = function();
    std::cout << p[0] + p[9] << '\n';
    delete[] p;
}

请注意,99% 的时间返回 std::vector&lt;int&gt;std::array&lt;int, 10&gt; 是一个更好的主意,而 99% 的剩余时间最好返回 std::unique_ptr&lt;int[]&gt;,调用者可以将其转移到自己的位置变量,它将delete[] 数据因为超出范围而被销毁,或者 - 对于成员变量 - 包含对象的销毁。

2) 返回指向 function()-local static 数组的指针(每次调用 function 时都会覆盖该数组,这样旧的返回指针将看到更新的值,并且在多线程中可能存在竞争条件代码):

auto function(int i) -> int(*)[10]{
    static int a[10] { 1, 39, ..., -3 };
    return &a;
}

调用者以同样的方式调用,但不得调用delete[]

【讨论】:

  • int (*p)[10] = new int[10]; 无法编译
  • 返回类型与第一个示例中返回对象的类型不匹配。并且需要返回静态数组的地址(return &amp;a)。
  • 数组类型很难动态处理。普通的new 是一种痛苦(正如您所发现的那样),placement-new 是完全不可能的,并且分配器无法创建它们。用于数组的新 make_shared 充其量只是一个 hack。
【解决方案3】:
#include <iostream>

const size_t sz = 10;

auto func(int i) -> int(*)[sz] /// returns a pointer to an array of ten ints
{
static int arr[sz];

for (size_t i = 0; i != sz; ++i)
    arr[i] = i;

return &arr;
}

int main()
{
int i = 2;
int (*p)[sz] = func(i); /// points to an array of ten ints which funct returns which is arr array

for (size_t ind = 0; ind != sz; ++ind) /// displays the values
    std::cout << (*p)[ind] << std::endl;

return 0;
}

自动函数 (int i) -> int(*)[sz]

  • 这意味着函数名称 funct 有一个 int 参数,它接受
    一个 int 参数并返回一个指向 10 个 int 数组的指针,这意味着 我们将每个 int 元素都指向了一个由十个 int 组成的数组。尾随返回类型用于方便阅读

返回一个指向十个整数数组的指针

int i = 2; int (*p)[sz] = 函数(i);

  • 这意味着 (*p)[sz] 将指向一个 func 函数的 10 个整数数组 返回哪个是 arr 数组并使用循环显示值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 2011-11-07
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多