Saturday, May 26, 2018

c++ - Allocating a vector vs. a pointer to a vector




Say I have two sets of code,



std::vectorv1;


and




std::vector *pV2 = new std::vector(10);


What is the difference between the two other than the fact that you will have a larger chunk of memory allocated with the pointer to the vector? Is there an advantage to one vs. the other?



In my mind, it seems like allocating the pointer is just more of a hassle because you have to deal with deallocating it later.


Answer





What is the difference between the two other than the fact that you will have a larger chunk of memory allocated with the pointer to the vector?







  1. 'will have a larger chunk of memory allocated'
    This isn't necessarily true! The std::vector might choose a much larger default initial size for the internally managed data array than 10.

  2. 'What is the difference between the two'
    The main difference is that the 1st one is allocated on the local scopes stack,
    and the 2nd one (usually) goes to the heap. Note: The internally managed data array goes to the heap anyway!!



To ensure proper memory management when you really have to use a std::vector* pointer allocated from the heap, I'd recommend the use of smart pointers, e.g.:




std::unique_ptr > pV2(new std::vector(10));


For more details have a look at the documentation of .


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...