Saturday 28 December 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...