简体   繁体   English

使用向量作为成员的结构的C ++大小

[英]C++ Size of Struct with Vectors as Members

I have a struct which has some vectors as members: 我有一个结构,其中有一些向量作为成员:

struct my_struct
{
    std::vector<int> x;
//  more members here
};

and an instance of my_struct: 和my_struct的一个实例:

my_struct A;

The vector(s) inside the struct can obviously change during the program's execution, with statements such as 结构中的向量在程序执行期间显然会发生变化,例如

A.x.resize(...);

or Axpush_back(...); 或Axpush_back(...);

My question is, is there any way to know the size in memory of A at some point during the program? 我的问题是,有没有办法在程序中的某个时刻知道A的内存大小? sizeof(A) does not return the correct answer, because of the vector members. 由于向量成员,sizeof(A)不返回正确答案。

The size of the vector will not influence the size of your struct, since a vector allocates memory to hold objects on the heap, with the default allocators at least. 向量的大小不会影响结构的大小,因为向量会分配内存来保存堆上的对象,至少使用默认的分配器。 Also, when writing your struct contents to a file, the objects that the vector holds will never be written, only the values of the vector's data members. 此外,在将结构内容写入文件时,将永远不会写入向量所包含的对象,只会写入向量的数据成员的值。 The objects are referenced by the vector in a pointer of some kind, so what is written to the file is the value of the pointer (an address), not the data it points to. 对象在某种指针中由向量引用,因此写入文件的是指针(地址)的值,而不是它指向的数据。 To write the vector and its objects to a file, you'll need to implement that yourself. 要将向量及其对象写入文件,您需要自己实现。 Perhaps boost serialize may be of some help here. 也许提升序列化可能会有所帮助。

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

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