Stackoverflow由于函数的大型返回类型

Dar*_*ieb 7 c++ stack-overflow function return-type

我的代码:

#include <iostream>
#include <array>

using namespace std;

array< array<int, 1000>, 1000 > largeThing;

array< array<int, 1000>, 1000 > functionFoo() {        
    return largeThing;
}

void main(){
    functionFoo();
    return;
}
Run Code Online (Sandbox Code Playgroud)

如果我运行这个我得到一个Stackoverflow错误.我到目前为止,其原因是functionFoo()的返回类型很大,因为返回值实际上是在堆上.

题:

如何使用具有大型返回类型的函数,以便函数将放在堆栈上的所有内存都放在堆上?

编辑:

我刚刚增加了stacksize,它运行正常.

zet*_*t42 5

std::array 在堆栈上分配,这取决于您的构建设置可能相对较小(典型大小为1 MiB).

如果你需要更大的东西,你可以在堆上显式分配该数组并返回一个指针.在std::unique_ptr本例中为一个智能指针当指针超出范围是负责释放的,所以我们不必记住调用delete.

using bigarray = std::array< std::array<int, 1000>, 1000 >;

std::unique_ptr< bigarray > functionFoo() {        
   return std::make_unique< bigarray >();
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用已经在堆上管理内存的不同类,例如std::vector:

std::vector< std::vector<int> > functionFoo() {        
    std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
    return largeThing;
}
Run Code Online (Sandbox Code Playgroud)


MSa*_*ers 5

到目前为止,最简单的解决方案是使用vector而不是array.这将使用std::allocatoraka"堆".