When do you worry about stack size?

前端 未结 19 1222
难免孤独
难免孤独 2020-12-10 12:41

When you are programming in a language that allows you to use automatic allocation for very large objects, when and how do you worry about stack size? Are there any rules o

19条回答
  •  星月不相逢
    2020-12-10 13:29

    When you are programming in a language that allows you to use automatic allocation for very large objects ...

    If I want to allocate a very large object, then instead of on the stack I might allocate it on the heap but wrapped in an auto_ptr (in which case it will be deallocated when it goes out of scope, just like a stack-resident object, but without worrying about stack size).

    ... when and how do you worry about stack size?

    I use the stack conservatively out of habit (e.g. any object bigger than about 512 bytes is allocated on the heap instead), and I know how big the stack is (e.g. about a megabyte by default), and therefore know that I don't need to worry about it.

    Are there any rules of thumb for reasoning about stack size?

    • Very big objects can blow the stack
    • Very deep recursion can blow the stack
    • The default stack size might be too big (take too much total memory) if there are many threads and if you're running on a limited-memory embedded device, in which case you might want to use an O/S API or linker option to reduce the size of the stack per thread.

提交回复
热议问题