The compiler freezes when initializing large std :: arrays

I need to initialize a very large multidimensional std::array data std::array :

 class Thing; class World { public: World() : space{nullptr} {}; ~World() = default; private: static unsigned int const size = 1000; std::array<std::array<std::array<std::unique_ptr<Thing>, size>, size>, size> space; }; 

If you try to create an instance, g ++ 4.8.2 throttles: it consumes all available memory and does not return. That is, the compiler freezes, and I never get the executable. Why is this? Please note that clang ++ has no problems.

Note. I fully understand that multiple data on the stack can overflow it. What is the best way to initialize it on the heap? I think creating a space link (for allocated memory) would be a better way, but I can't understand the syntax.

+6
source share
3 answers

Well, I can’t explain the nuance about why g ++ is suggesting this, but until you do, consider this to declare your member:

 std::vector<std::array<std::array<std::unique_ptr<Thing>,size>,size>> space; 

and in the constructor initializer list:

 World() : space{size} 

That should at least get you to compile and move it all in a heap. Note: it would be a better 64-bit process. I will have to hunt to find out why g ++ is doing what I suspect is doing.

+2
source

As you use unique_ptr , it looks like you are looking for a sparse type of 3D matrix. To implement a sparse matrix, you can take a look at What is the best way to create a sparse array in C ++? , and as part of the implementation, you can use the Boost Multi-index for quick access to all dimensions.

+3
source
 vector<vector<vector<unique_ptr<Thing>>>> space; 

and upon initialization:

 for (int i = 0; i < 1000; i++) { vector<vector<unique_ptr<Thing>>> sp1; for (int j = 0; j < 1000; j++) { vector<unique_ptr<Thing>> sp2; for (int k = 0; k < 1000; k++) sp2.push_back(make_unique<Thing>("params", "to", "construct", "thing")); sp1.push_back(move(sp2)); } space.push_back(move(sp1)); } 

It looks like your approach, but it creates vectors on the heap, not on the stack.

0
source

All Articles