简体   繁体   中英

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 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(...);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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