C++ Any benifits using pointer to vector of pointers?

半世苍凉 提交于 2019-12-08 14:08:48

问题


Before I start, I have already looked at these questions:

Memory consumption of a pointer to vector of pointers

Pointer to vector vs vector of pointers vs pointer to vector of pointers

And they both do not answer my question.


I am working on a project where it involves millions of instances to work with.

The data structure I am using is a bit complicated to look at for the first time, the structure itself isn't really of any importance for this question.

Now, if I had the following:

vector<object*> *myVector;

Everything goes to the heap.

However, what happens if I used this:

vector<object*> myVector;

Does the vector itself get stored on the stack? And its contents are then stored on the heap? For example, if the vector had 10 million instances, would I have 10 million references on the stack for 10 million objects on the heap? Or am I missing something?

Moreover, if I used this:

vector<object> *myVector;

Where do the contents of the vector go? Does everything go on the heap? If yes, then does it work recursively? For example:

vector<vector<vector<int>>> *myVector;

Are all the inner vectors then stored on the heap? If yes, then it should be enough deleting myVector in the destructor, without worrying on anything else?

Anyway, I am assuming all the answers that apply to vector would also apply to unordered_map. Please tell me if I am wrong.

Thanks in advance.


回答1:


In general, elements of a std::vector will always be dynamically allocated on the heap. For most implementations, a std::vector<T> foo, where T could be a pointer or not, there will always be three pointers on the stack that describe the vector itself, but not the elements. For a std::vector<T> *bar, there is one pointer, bar, on stack. The three vector pointers as well as the vector elements are on the heap.

Similarly, for an std::unordered_map, the elements itself will always be dynamically allocated on the heap. Generally, any std type that has a Allocator template parameter, or any type that contains a variable amount of data, will have it's data dynamically allocated on the heap.

Now there are special cases, like custom allocators, weird optimizations, specifics of terminology, but for practical purposes, this is what you should know.

The next thing that you might want to learn about, are smart pointers, e.g. std::unique_ptr, and std::shared_ptr, ownership semantics and RAII. That is actually more important to know in order to write correct code (What do I need to delete and worry about?).



来源:https://stackoverflow.com/questions/43154586/c-any-benifits-using-pointer-to-vector-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!