由于 return 类型的函数导致 Stackoverflow
Stackoverflow due to large return type of a function
这是我的代码:
#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;
}
如果我 运行 这会出现 Whosebug 错误。到目前为止,我知道这是因为 functionFoo() 的大 return 类型,因为 return 值实际上在堆上。
问题:
如何使用大型 return 类型的函数,以便函数将放在堆栈上的所有内存都放在堆上?
编辑:
我只是增加了堆栈大小,效果很好。
std::array
分配在堆栈上,根据您的构建设置,它可能相对较小(典型大小为 1 MiB)。
如果您需要更大的东西,您可以显式地在堆上分配该数组并 return 一个指针。本例中的 std::unique_ptr
是一个智能指针,当指针超出范围时负责重新分配,因此我们不必记住调用 delete
.
using bigarray = std::array< std::array<int, 1000>, 1000 >;
std::unique_ptr< bigarray > functionFoo() {
return std::make_unique< bigarray >();
}
另一种方法是使用已经在堆上管理内存的不同 class,例如 std::vector
:
std::vector< std::vector<int> > functionFoo() {
std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
return largeThing;
}
到目前为止,最简单的解决方案是使用 vector
而不是 array
。这将使用 std::allocator
又名 "the heap"。
这是我的代码:
#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;
}
如果我 运行 这会出现 Whosebug 错误。到目前为止,我知道这是因为 functionFoo() 的大 return 类型,因为 return 值实际上在堆上。
问题:
如何使用大型 return 类型的函数,以便函数将放在堆栈上的所有内存都放在堆上?
编辑:
我只是增加了堆栈大小,效果很好。
std::array
分配在堆栈上,根据您的构建设置,它可能相对较小(典型大小为 1 MiB)。
如果您需要更大的东西,您可以显式地在堆上分配该数组并 return 一个指针。本例中的 std::unique_ptr
是一个智能指针,当指针超出范围时负责重新分配,因此我们不必记住调用 delete
.
using bigarray = std::array< std::array<int, 1000>, 1000 >;
std::unique_ptr< bigarray > functionFoo() {
return std::make_unique< bigarray >();
}
另一种方法是使用已经在堆上管理内存的不同 class,例如 std::vector
:
std::vector< std::vector<int> > functionFoo() {
std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
return largeThing;
}
到目前为止,最简单的解决方案是使用 vector
而不是 array
。这将使用 std::allocator
又名 "the heap"。