简体   繁体   中英

Can a class member offset change if a vector member changes size?

If I have a class like:

class foo 
{
    std::vector<int> bar;
    int a;
};

will the offset of int a stay constant throughout runtime? My understanding is that std::vector<int> bar can be resized and that vectors have the items they contain in contiguous memory. If this is the case, then if bar gets resized during runtime, wouldn't that change the offset of a ?

In C++ no object changes its size at run time — all complete types are of known and constant size. This is reflected by the fact that the result of the sizeof operator is a constexpr; it is determined at compile time.

It is well possible and indeed not uncommon that an object contains a pointer which may over the course of the run time point to memory of varying sizes; but that memory resides elsewhere and is unrelated to the object (except for the coincidental fact that a pointer in the object points to it). In particular, it is not nominally part of the object and does not influence its size. std::vector is such a type containing a pointer. Where that pointer points to, and how much memory is available at that location, does not affect the size of the vector object as such.

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