Heap vs Stack allocation

后端 未结 4 847
醉梦人生
醉梦人生 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条回答
  •  醉酒成梦
    2020-12-03 09:12

    General rule:

    • when you use new or new [], you allocate on heap, in other case you allocate on stack.

    • every time you use new you should use delete (explicitly or not)

    • every time you use new[] you should use delete[] (explicitly or not)

    The next code is UB since you use one new[] and 101 delete. Use one delete[].

    Vector** v = new Vector*[100];
    for (int i = 0; i < 100; ++i)
    {
       delete(v[i]);
    }
    delete(v);
    

提交回复
热议问题