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

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

    But I can't figure out why should we use it like this?

    I will compare how it works inside the function body if you use:

    Object myObject;
    

    Inside the function, your myObject will get destroyed once this function returns. So this is useful if you don't need your object outside your function. This object will be put on current thread stack.

    If you write inside function body:

     Object *myObject = new Object;
    

    then Object class instance pointed by myObject will not get destroyed once the function ends, and allocation is on the heap.

    Now if you are Java programmer, then the second example is closer to how object allocation works under java. This line: Object *myObject = new Object; is equivalent to java: Object myObject = new Object();. The difference is that under java myObject will get garbage collected, while under c++ it will not get freed, you must somewhere explicitly call `delete myObject;' otherwise you will introduce memory leaks.

    Since c++11 you can use safe ways of dynamic allocations: new Object, by storing values in shared_ptr/unique_ptr.

    std::shared_ptr safe_str = make_shared("make_shared");
    
    // since c++14
    std::unique_ptr safe_str = make_unique("make_shared"); 
    

    also, objects are very often stored in containers, like map-s or vector-s, they will automatically manage a lifetime of your objects.

提交回复
热议问题