What is the overhead cost of an empty vector?

后端 未结 6 1491
野性不改
野性不改 2020-12-06 04:24

What is the memory overhead of having an empty vector vs having a pointer to a vector?

Option A:

std::vector v;

Option B

相关标签:
6条回答
  • 2020-12-06 04:39

    Implementation dependant, probably a pointer and two integers for current size and capacity.

    0 讨论(0)
  • 2020-12-06 04:46

    As for the question as asked: It depends on the implementation. With MSVC 7.1 this:

    std:: cout << sizeof(std::vector<int>) << std::endl;
    

    gives me 16 (bytes). (3 pointers: begin, end, and end of capacity, plus an allocator)

    However it should be noted that the pointer-to-vector gives it a larger overhead:

    • in both time and space in the non-empty case
    • in complexity in all cases.
    0 讨论(0)
  • 2020-12-06 04:52

    VS2005:

    std::vector<int> *ptrToVec = new std::vector<int>();
    std::vector<int> vecOfInt;
    
    sizeof(ptrToVec) = 4
    sizeof(vecOfInt) = 20
    

    Thanks!

    0 讨论(0)
  • 2020-12-06 04:54

    It's completely implementation-dependent and you should neither assume nor rely on the details. For what it's worth it's 20-bytes using VC.

    0 讨论(0)
  • 2020-12-06 04:55

    In Visual Studio Community 2017 (Version 15.2), running this code:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void main()
    {
        vector<float> test;
        vector<float>* test2 = &test;
        cout << sizeof(test) << "\n";
        cout << sizeof(test2) << "\n";
    
        cout << "\n";
        system("pause");
    }
    

    Running in 32 bit (x86), I get 16 bytes for the vector and 4 bytes for the vector pointer.

    Running in 64 bit (x64), I get 32 bytes for the vector and 8 bytes for the vector pointer.

    0 讨论(0)
  • 2020-12-06 05:05

    std::vector v; takes up sizeof(v) space. It might vary by implementation, so run it and find out how much it takes for you.

    0 讨论(0)
提交回复
热议问题