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

前端 未结 4 554
天命终不由人
天命终不由人 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:42

    I prefer to allocate on the stack, for two reasons. First, all else being equal, it is faster than heap. Also, the deallocation happens automatically, I don't need to rememeber to delete it (of course, there are auto_ptrs and such to help with that).

    a pointer is really needed

    It is OK to pass a pointer to an object on the stack. Just make sure the user of that pointer does not access the object after its lifetime expires.

    the class or array is too big for the stack

    Only for really big things should this matter. You've probably got 1MB of stack, so you can put about 1000 1KB objects before there's a problem.

    inheritance requires it

    Why would it?

    something else?

    The lifetime required of the object is longer than the lifetime of the stack frame. This is the principal reason to allocate on the heap.

提交回复
热议问题