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

后端 未结 22 1685
予麋鹿
予麋鹿 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-21 23:53

    In C++, objects allocated on the stack (using Object object; statement within a block) will only live within the scope they are declared in. When the block of code finishes execution, the object declared are destroyed. Whereas if you allocate memory on heap, using Object* obj = new Object(), they continue to live in heap until you call delete obj.

    I would create an object on heap when I like to use the object not only in the block of code which declared/allocated it.

提交回复
热议问题