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

后端 未结 22 1684
予麋鹿
予麋鹿 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:10

    There are many benefits of using pointers to object -

    1. Efficiency (as you already pointed out). Passing objects to functions mean creating new copies of object.
    2. Working with objects from third party libraries. If your object belongs to a third party code and the authors intend the usage of their objects through pointers only (no copy constructors etc) the only way you can pass around this object is using pointers. Passing by value may cause issues. (Deep copy / shallow copy issues).
    3. if the object owns a resource and you want that the ownership should not be sahred with other objects.

提交回复
热议问题