C++ Object Creation and Memory Allocation

前端 未结 5 1316
一整个雨季
一整个雨季 2021-01-28 10:14

Let\'s say I have a simple Movie object that just keeps track of a few data members of name, length and cost.

If in my driver file, I create a Movie object. Which is pre

5条回答
  •  暖寄归人
    2021-01-28 10:58

    I think you understand the difference between the two fine. Instead, the question is "which should I prefer?" Personally, if I can get away with it, I prefer to put things on the stack. Nowadays your stack is large enough that you won't get a stack overflow unless you have some other bug, and putting things on the stack means (1) there's no need to delete it by hand, (2) it's more likely to be in the memory cache than stuff on the heap, and (3) allocating the memory is as fast as you can get.

    However, there are times that you can't get away with it. In those cases, go ahead and put things on the heap.

    The confusion comes from Gosling's strange insistence on using new to mean "make me an object." Java documentation always brags about how you don't need to delete things that you new-ed up (because of the garbage collector) but never seems to mention that in C++ you don't have to new things up nearly as often as in Java.

提交回复
热议问题