How to correctly deallocate or delete a c++ vector?

前端 未结 6 1675
灰色年华
灰色年华 2021-01-25 11:00

I have a weird problem with vector in C++..

I created a vector and inserted 10000 integer values into it and have checked the memory utilization. It is 600 kb. But after

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-25 11:48

    The following code gives the answer:

    #include 
    #include 
    
    struct Foo
    {
        ~Foo()
        {
            printf("~Foo()\n");
        }
    };
    
    int main()
    {
        std::vector v;
    
        v.push_back(Foo());
    
        // This causes all Foo instances to be released as well as all
        // space allocated by the vector to be released.
        v = std::vector();
    
        // As you can see, all printf("~Foo()\n") calls happen before this
        // line is printed.
        printf("~~~~~~~~~~~~~~\n");
    
        return 0;
    }
    

提交回复
热议问题