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

后端 未结 22 1651
予麋鹿
予麋鹿 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 excellent answers already, but let me give you one example:

    I have an simple Item class:

     class Item
        {
        public: 
          std::string name;
          int weight;
          int price;
        };
    

    I make a vector to hold a bunch of them.

    std::vector inventory;

    I create one million Item objects, and push them back onto the vector. I sort the vector by name, and then do a simple iterative binary search for a particular item name. I test the program, and it takes over 8 minutes to finish executing. Then I change my inventory vector like so:

    std::vector inventory;

    ...and create my million Item objects via new. The ONLY changes I make to my code are to use the pointers to Items, excepting a loop I add for memory cleanup at the end. That program runs in under 40 seconds, or better than a 10x speed increase. EDIT: The code is at http://pastebin.com/DK24SPeW With compiler optimizations it shows only a 3.4x increase on the machine I just tested it on, which is still considerable.

提交回复
热议问题