简体   繁体   中英

Basic - shared_ptr to vector of vectors of values

I have a vector of a vectors of objects containing just a few integers.

The outer vector holds hundreds of vectors, those hold thousands to hundreds of thousands of Data objects.

I am using a library with a lot of shared_ptr's involved, so that's what i'll be using.

How do I store this so that the data is stored to the heap?

std::vector<std::shared_ptr<std::vector<Data>>>
std::vector<std::vector<std::shared_ptr<Data>>>

etc

What is the correct way to handle this?

To store something on the heap you use new in c++ or malloc in c. Although I believe that the vector implementation does use the heap since vector is a dynamically sized container. So in reality if you add an element to a vector that elemenet is already on the heap unless it is a pointer in which case just the pointer is on the heap and not the element that the pointer points to as @Oswald points out.

How do I store this so that the data is stored to the heap?

If you need reference semantics , ie if you need the values in the container to be aliases for values which are also referred to from other parts of the code, and modifications made in one part of the code should be visible for other parts that hold an alias to the modified Data object, I would say this is the right container definition:

std::vector<std::vector<std::shared_ptr<Data>>>

For what concerns your question about where the storage comes from, std::vector always allocates its elements dynamically in a continuous region of storage, no matter whether those are shared_ptr s, vector s, or Data s.

However, I would recommend you to think if you really need reference semantics, or if it is not enough to store objects of type Data by value inside the containers:

std::vector<std::vector<Data>>

This would simplify your code and you would also get rid of the shared_ptr memory and run-time overhead.

Whether or not you need reference semantics is something that only you, as the designer of your application, can tell. The information you provided is not enough for me to tell it without uncertainty, but hopefully this answer gave you a hint on the kind questions you should ask yourself, and what would be the answer in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM