When should a class be allocated on the stack instead of the heap

前端 未结 4 578
天命终不由人
天命终不由人 2021-01-11 12:11

In the past whenever I needed to create an instance of a class I would use new to allocate it on the heap (except for stl classes, and math classes like vec3 and mat4).

4条回答
  •  忘掉有多难
    2021-01-11 12:48

    When should a class be allocated on the stack instead of the heap?

    Whenever possible and not a great inconvenience. There will be exceptions, but to answer your question as a general rule: When creating an instance, new/new[] should be typed less than one percent of the time.


    a pointer is really needed (ie the lifetime of the object to outlast the scope of declaration)

    Yes, in appropriate cases. Judging by your use of the heap described in the OP, this is likely going to be necessary far less often than you believe.

    the class or array is too big for the stack

    Yes, but that should not be much of a concern -- a class that large typically indicates that something is fundamentally wrong with your class. Client friendly classes might consider creating those huge, fixed sized arrays on the heap.

    inheritance requires it (abstract base class/interface)

    In some cases (e.g. where an abstract factory or deep clone of polymorphic type is present), but then it is the factory that creates the type, and the problem is often shifted away from your program's use of the stack before you can consider it.

    something else?

    No


    The reasons:

    • it's clear, succinct, and its lifetime and scope are well determined.
    • less resource consumption.
    • fewer memory related bugs or things that could go wrong.
    • speed. the stack allocation is very fast. fewer locks.

提交回复
热议问题