bluebass44
bluebass44

Reputation: 65

Struct memory locations of member variables

I have a struct that contains many variables of several types including vectors. Is it safe to store a pointer to the non-vector variables? I suspect when the vectors resize it is possible they will have to be moved to a different memory location. Does that also mean the rest of the variables may move?

Upvotes: 0

Views: 194

Answers (2)

Raildex
Raildex

Reputation: 4747

Is it safe to store a pointer to the non-vector variables?

Yes, as long as the struct itself doesn't move or gets destroyed (by leaving the scope or deleting it)

I suspect when the vectors resize it is possible they will have to be moved to a different memory location

You don't seem to understand how vectors work. What you store in your struct is not the "vector" itself, but just information about it. The actual data (i.e. your structs within the vector) are dynamically (re-)allocated on the free-store during runtime.

Side note: If you know the size of the vector at compile time, you can use std::array, it has similar semantics like vector, but is an actual fixed-size array (changing array size changes sizeof the struct it is contained in.)

Upvotes: 0

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

I suspect when the vectors resize it is possible they will have to be moved to a different memory location. Does that also mean the rest of the variables may move?

std::vector does not store its elements inside the class. It stores them on the free-store and manages its own memory. Size of a class/struct is a constant expression and cannot change dynamically.

Is it safe to store a pointer to the non-vector variables?

Yes, of course. As long as the structure itself is valid, all pointers to its fields are also valid.

Upvotes: 2

Related Questions