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?
- 'will
have a larger chunk of memory allocated'
This isn't necessarily
true! Thestd::vector
might choose a much larger
default initial size for the internally managed data array
than10
. - '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 class="post-tag" title="show questions tagged 'c++'" rel="tag">c++ smart
pointers,
e.g.:
std::unique_ptr
> pV2(new
std::vector(10));
For
more details have a look at the documentation of href="http://en.cppreference.com/w/cpp/memory"
rel="nofollow">
.
No comments:
Post a Comment