Why should I use a pointer rather than the object itself?

后端 未结 22 1658
予麋鹿
予麋鹿 2020-11-21 23:26

I\'m coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than t

22条回答
  •  礼貌的吻别
    2020-11-22 00:05

    Object *myObject = new Object;
    

    Doing this will create a reference to an Object (on the heap) which has to be deleted explicitly to avoid memory leak.

    Object myObject;
    

    Doing this will create an object(myObject) of the automatic type (on the stack) that will be automatically deleted when the object(myObject) goes out of scope.

提交回复
热议问题