I've got a doubt about using std::vector
.
If I got a structure with a std::vector
object with nondefined space in the memory, if it need to be reallocate (the std::vector
), is the structure also reallocated? or only the std::vector
?
For example:
struct cluster{
int a;
int b;
struct cluster* parent;
vector<struct cluster> children;
}
struct cluster obj = {2,1,...};
struct cluster *pobj = &obj;
for(int i = 0; i < 100 ; i ++){
children.push_back(i); //The capacity will be increased progressly, no?
}
So, the question is: is pobj==&obj
at the end of for
loop? Or is obj
reallocated because of the reallocation of child std::vector
object?
I hope I explained my doubt. Thanks for your time.
No, your obj
variable is never reallocated because members inside it change. The vector have its own pointers to its data, and handles all its own allocations and reallocations internally.
Think about it this way: Normally local variables (including full structures and arrays) are put on the stack of the current function. The compiler accesses these variables through an offset from a base address. If the compiler (or system) suddenly started to move variables around in memory it would complicate variable access considerably and also affect runtime speed and efficiency of your program quite a lot. So local variables are on the stack, and stays where they were put by the compiler. Data allocated on the heap (like the data inside a std::vector
) can be easily moved around since all that has to be updated in the pointer to the data, and like I said before it's all handled internally in the vector object so nothing you would notice anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With