简体   繁体   中英

std::vector of Base class with Derived objects

I have a deque of std::shared_ptr declared has a deque of a base class (let's call it Polygon) but I'm storing on it pointers to derived objecs (for example Triangle). I'm thinking now about change the data structure to be a std::vector to use the fact that vector ensures adjacent memory but I have a couple of questions here:

1) Is this possible even if the objects have different sizes? Or can happen that due to the derived objects are bigger than the base one they are going to overlap in memory?

2) Storing std::shared_ptr I'm not going to have them literally together in memory just the pointers is it true? Or am I wrong?

Thanks

Is this possible even if the objects have different sizes? Or can happen that due to the derived objects are bigger than the base one they are going to overlap in memory?

This is fine. Even though Derived can be larger than Base you aren't actually storing those in the vector. You are storing a pointer to them and the pointer is always the same size.

Storing std::shared_ptr I'm not going to have them literally together in memory just the pointers is it true? Or am I wrong?

Correct, the pointers will sit next to each other in the vector, but what they point to could be anywhere in memory.

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