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

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

    Technically it is a memory allocation issue, however here are two more practical aspects of this. It has to do with two things: 1) Scope, when you define an object without a pointer you will no longer be able to access it after the code block it is defined in, whereas if you define a pointer with "new" then you can access it from anywhere you have a pointer to this memory until you call "delete" on the same pointer. 2) If you want to pass arguments to a function you want to pass a pointer or a reference in order to be more efficient. When you pass an Object then the object is copied, if this is an object that uses a lot of memory this might be CPU consuming (e.g. you copy a vector full of data). When you pass a pointer all you pass is one int (depending of implementation but most of them are one int).

    Other than that you need to understand that "new" allocates memory on the heap that needs to be freed at some point. When you don't have to use "new" I suggest you use a regular object definition "on the stack".

    0 讨论(0)
  • 2020-11-21 23:56

    This is has been discussed at length, but in Java everything is a pointer. It makes no distinction between stack and heap allocations (all objects are allocated on the heap), so you don't realize you're using pointers. In C++, you can mix the two, depending on your memory requirements. Performance and memory usage is more deterministic in C++ (duh).

    0 讨论(0)
  • 2020-11-21 23:57

    Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.

    Another thing you mentioned in your question:

    Object *myObject = new Object;
    

    How does it work? It creates pointer of Object type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new), you also have to free memory manually, that means in code you should have:

    delete myObject;
    

    This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.


    And now some introduction is over and go back to question.

    You can use pointers instead of objects to get better performance while transferring data between function.

    Take a look, you have std::string (it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...) which can be declarated in different ways:

    1. void foo(std::string xml); In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.
    2. void foo(std::string* xml); In this case you will pass pointer to object, same speed as passing size_t variable, however this declaration has error prone, because you can pass NULL pointer or invalid pointer. Pointers usually used in C because it doesn't have references.
    3. void foo(std::string& xml); Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).
    4. void foo(const std::string* xml); Here is the same as second, just pointer value cannot be changed.
    5. void foo(const std::string& xml); Here is the same as third, but object value cannot be changed.

    What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new or regular).


    Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string is also container, some guys forgot it :)

    0 讨论(0)
  • 2020-11-21 23:57

    In areas where memory utilization is at its premium , pointers comes handy. For example consider a minimax algorithm, where thousands of nodes will be generated using recursive routine, and later use them to evaluate the next best move in game, ability to deallocate or reset (as in smart pointers) significantly reduces memory consumption. Whereas the non-pointer variable continues to occupy space till it's recursive call returns a value.

    0 讨论(0)
  • 2020-11-21 23:58

    I will include one important use case of pointer. When you are storing some object in the base class, but it could be polymorphic.

    Class Base1 {
    };
    
    Class Derived1 : public Base1 {
    };
    
    
    Class Base2 {
      Base *bObj;
      virtual void createMemerObects() = 0;
    };
    
    Class Derived2 {
      virtual void createMemerObects() {
        bObj = new Derived1();
      }
    };
    

    So in this case you can't declare bObj as an direct object, you have to have pointer.

    0 讨论(0)
  • 2020-11-21 23:59

    With pointers ,

    • can directly talk to the memory.

    • can prevent lot of memory leaks of a program by manipulating pointers.

    0 讨论(0)
提交回复
热议问题