简体   繁体   English

结构中的c ++向量

[英]c++ vector inside a structure

I've got a doubt about using std::vector . 我对使用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? 如果我在内存中有一个带有非定义空间的std::vector对象的结构,如果需要重新分配( std::vector ),结构是否也重新分配了? or only the std::vector ? 还是只有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? 所以,问题是:在for循环结束时是pobj==&obj吗? Or is obj reallocated because of the reallocation of child std::vector object? 或者obj重新分配,因为孩子再分配std::vector对象?

I hope I explained my doubt. 我希望我解释了我的怀疑。 Thanks for your time. 谢谢你的时间。

No, your obj variable is never reallocated because members inside it change. 不,你的obj变量永远不会被重新分配,因为它内部的成员会发生变化。 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. 在堆上分配的数据(比如std::vector的数据)可以很容易地移动,因为所有必须在指向数据的指针中更新,就像我之前所说的那样,它们都在vector对象内部处理所以没有无论如何你会注意到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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