What does std::vector look like in memory?

前端 未结 6 686
耶瑟儿~
耶瑟儿~ 2021-02-01 13:10

I read that std::vector should be contiguous. My understanding is, that its elements should be stored together, not spread out across the memory. I have simply acce

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 13:37

    In terms of the actual structure, an std::vector looks something like this in memory:

    struct vector {    // Simple C struct as example (T is the type supplied by the template)
      T *begin;        // vector::begin() probably returns this value
      T *end;          // vector::end() probably returns this value
      T *end_capacity; // First non-valid address
      // Allocator state might be stored here (most allocators are stateless)
    };
    

    Relevant code snippet from the libc++ implementation as used by LLVM

    Printing the raw memory contents of an std::vector:
    (Don't do this if you don't know what you're doing!)

    #include 
    #include 
    
    struct vector {
        int *begin;
        int *end;
        int *end_capacity;
    };
    
    int main() {
        union vecunion {
            std::vector stdvec;
            vector           myvec;
            ~vecunion() { /* do nothing */ }
        } vec = { std::vector() };
        union veciterator {
            std::vector::iterator stditer;
            int                       *myiter;
            ~veciterator() { /* do nothing */ }
        };
    
        vec.stdvec.push_back(1); // Add something so we don't have an empty vector
    
        std::cout
          << "vec.begin          = " << vec.myvec.begin << "\n"
          << "vec.end            = " << vec.myvec.end << "\n"
          << "vec.end_capacity   = " << vec.myvec.end_capacity << "\n"
          << "vec's size         = " << vec.myvec.end - vec.myvec.begin << "\n"
          << "vec's capacity     = " << vec.myvec.end_capacity - vec.myvec.begin << "\n"
          << "vector::begin()    = " << (veciterator { vec.stdvec.begin() }).myiter << "\n"
          << "vector::end()      = " << (veciterator { vec.stdvec.end()   }).myiter << "\n"
          << "vector::size()     = " << vec.stdvec.size() << "\n"
          << "vector::capacity() = " << vec.stdvec.capacity() << "\n"
          ;
    }
    

提交回复
热议问题