Вопрос

Consider the situation where there is some std::vector<ClassA> and then there are objects of another class that contain pointers to elements of this vector, e.g.:

ClassB Object(&ClassA[12]);

Is this a mine field, in case the vector gets resized, etc.? Should I have an std::vector<ClassA *> instead?

Это было полезно?

Решение

If the vector is resized (e.g. if a push_back() exceeeds vector's current capacity, so there is a need to allocate a bigger chunk of heap memory), then the addresses of vector elements change (so, extern pointers to vector's elements are invalidated).

If you store pointers to ClassA inside the vector, instead of direct instances of ClassA, then the pointers are still valid after vector resize.

However, note that storing owning raw pointers in a std::vector is a very bad thing, and source of leaks.
You should store owning smart pointers, e.g. std::unique_ptr (for unique ownership semantics) or std::shared_ptr (for shared ownership semantics).

For example, you can have a vector<unique_ptr<ClassA>> (so, the vector owns the dynamically allocated instances of ClassA), and you can have raw observing pointers (e.g. simple ClassA*) from an external object.

Другие советы

It is safe, as long as you are not storing that address for later usage (where something that causes the vector to resize or otherwise move the memory would leave you with a dangling pointer).

If you intend to hold onto that pointer, it would be better to have a vector of pointers (or a vector of smart pointers) instead:

std::vector<std::shared_ptr<ClassA>> myVector;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top