简体   繁体   English

C ++的向量如何分配内存

[英]How C++'s Vector Allocate Memory

Consider my code, I have vector P which type is Particle. 考虑我的代码,我有向量P,类型为粒子。 Then inside the Particle there's also has vector x, v and xBest. 然后在粒子内部还有向量x,v和xBest。

So, It's vectors inside of vector. 因此,它是向量内部的向量。

struct Particle
{
    vector<double> x;
    vector<double> v;
    vector<double> xBest;
    double fitness;
    double pBest;
};

class Swarm
{
  public:
    vector<Particle> P;
    Swarm();
};

Since the compiler won't let me reserve memory for vector when declaring a class or struct. 由于在声明类或结构时,编译器不会让我为vector保留内存。 like this: 像这样:

class Swarm
{
  public:
    vector<Particle> P(30);
    Swarm();
};

So, I do it in the constructor like this: 所以,我在构造函数中这样做:

Swarm::Swarm()
{
    P.reserve(30);
    for(size_t i = 0; i < 30; i++)
    {
        P[i].x.reserve(10);
        P[i].v.reserve(10); 
        P[i].xBest.reserve(10);         
    }
}

And it's work. 这是工作。

I'm very curious about this. 我对此很好奇。 Since the size of the vectors in struct Particle haven't been initialize yet so the size of Particle is unknown. 由于struct Particle中向量的大小尚未初始化,因此Particle的大小未知。 But I can reserve the memory for 30 Particles even before reserving the memory for 3 vector in struct Particle !! 但是即使在结构粒子中为3个向量保留内存之前,我也可以为30个粒子保留内存!

How is that possible? 那怎么可能?

This is undefined behavior. 这是未定义的行为。 When you reserve a vector, you don't create the objects, so the loop: reserve向量时,您不会创建对象,因此循环:

for(size_t i = 0; i < 30; i++)
{
    P[i].x.reserve(10);
    P[i].v.reserve(10); 
    P[i].xBest.reserve(10);         
}

Is calling reserve on vectors that DO NOT exist. 在不存在的向量上调用reserve

You can't reserve capacity on vectors that don't exist. 您不能在不存在的向量上保留容量。 You need to create your Particle s first. 您需要首先创建您的Particle

In C++ the storage needed by every object is known statically, ie at compile time. 在C ++中,静态(即在编译时)知道每个对象所需的存储。 There is no such thing as VLAs in C++. C ++中没有VLA这样的东西。 std::vector doesn't store the objects directly, it stores a pointer to an array on the heap: std::vector不直接存储对象,它存储指向堆上数组的指针:

template <typename T>
class vector {
    // For illustration purposes only
    T *array;
    std::size_t size;
};

As you can see, the size of the vector is always constant, no matter how many elements it points to which is why your example (minus the UB you have as mentioned in the comments) works. 如您所见,向量的大小始终是恒定的,无论它指向多少元素,这就是示例(减去注释中提到的UB)起作用的原因。

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

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