Heap vs Stack allocation

后端 未结 4 827
醉梦人生
醉梦人生 2020-12-03 08:47

I am alittle bit confused on topic of allocating objects on heap vs allocating on stack, and when and how delete() should be called.

For example I have class Vector.

4条回答
  •  -上瘾入骨i
    2020-12-03 09:08

    1. delete [] v; - it's an array notation of delete operator. You have to use it when deleting arrays, instead of deleting each element sequentially.
    2. Vector* v = Vector[100]; just won't compile. Write Vector v[100]; and it will allocate array of vectors on stack. You may not delete it manually.
    3. x, y, z are on the heap as the whole object is on the heap
    4. items[10] is also allocated on the heap as is makes part of the object. To delete it just call delete v2;. You don't need a special destructor unless you allocate anything in constructor.
    5. int* items; is stored on the stack as it's part of the object allocated on stack. You don't have to delete it, it will be deleted automatically when comes out of scope.

提交回复
热议问题