使用向量作为成员的结构的C ++大小(C++ Size of Struct with Vectors as Members)

编程入门 行业动态 更新时间:2024-10-26 05:17:33
使用向量作为成员的结构的C ++大小(C++ Size of Struct with Vectors as Members)

我有一个结构,其中有一些向量作为成员:

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

和my_struct的一个实例:

my_struct A;

结构中的向量在程序执行期间显然会发生变化,例如

A.x.resize(...);

或Axpush_back(...);

我的问题是,有没有办法在程序中的某个时刻知道A的内存大小? 由于向量成员,sizeof(A)不返回正确答案。

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 A;

The vector(s) inside the struct can obviously change during the program's execution, with statements such as

A.x.resize(...);

or A.x.push_back(...);

My question is, is there any way to know the size in memory of A at some point during the program? sizeof(A) does not return the correct answer, because of the vector members.

最满意答案

向量的大小不会影响结构的大小,因为向量会分配内存来保存堆上的对象,至少使用默认的分配器。 此外,在将结构内容写入文件时,将永远不会写入向量所包含的对象,只会写入向量的数据成员的值。 对象在某种指针中由向量引用,因此写入文件的是指针(地址)的值,而不是它指向的数据。 要将矢量及其对象写入文件,您需要自己实现。 也许提升序列化可能会有所帮助。

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.

更多推荐

本文发布于:2023-07-26 19:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1280275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   大小   成员   结构   Members

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!