Allocating a vector vs. a pointer to a vector
This question already has an answer here:
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?
This isn't necessarily true! The
std::vector
might choose a much larger default initial size for the internally managed data array than 10
. 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<float>*
pointer allocated from the heap, I'd recommend the use of c++ smart pointers, eg:
std::unique_ptr<std::vector<float> > pV2(new std::vector<float>(10));
For more details have a look at the documentation of <memory>
.
One of the critical differences is scope. In your first example, the vector will probably either be a member of a class, or it will be local to a function. If it's a class member, it will be destroyed when the containing object is destroyed. If it's local to a function, it will be destroyed when the function ends. The object absolutely cannot exist beyond that, so you have to be very careful if you try passing its address to another part of your program.
When you manually allocate something on the heap instead, it will exist for as long as you want. You're in complete control of the deallocation, which means you can create it in one object/function, and use or delete it in another whenever you need to.
It's also quite useful in various situations to be able to delay instantiation of an object until it's actually required. For example, it may need different construction parameters depending on user input, or you may want to take advantage of polymorphism (ie decide at runtime which sub-class to instantiate).
Another key difference for some situations is available memory. If you create an object locally to a function, it will reside on the stack. There is a lot less space available on the stack than on the heap, so you can run into difficulties when using particularly large objects (although that won't happen with a vector because it allocates on the heap internally anyway).
It's worth noting that the actual amount of memory used by the object is the same, whether it's on the stack or on the heap. The only difference is that if you manually allocate something on the heap, then you will also have a pointer to it. That's only an extra 4 or 8 bytes though, which is negligible in most cases.
链接地址: http://www.djcxy.com/p/40644.html上一篇: C ++中没有“new”关键字的内存分配
下一篇: 分配矢量与指向矢量的指针