Can I force std::vector to leave a memory leak?

前端 未结 7 944
日久生厌
日久生厌 2021-01-18 00:45

Can I force std::vector to not deallocate its memory after the vector goes out of scope?

For example, if I have



        
7条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 01:46

    The vector is desiged to prevent leaks.

    But if you want to shoot yourself in the foot, it's possible. Here's how you prevent the vector from deallocating its internal array:

    int *foo()
    {
        std::vector v(10,1);
    
        int *ret = v.data();
        new (&v) std::vector; // Replace `v` with an empty vector. Old storage is leaked.
        return ret;
    }
    

    As the other answers say, you should never do it.

提交回复
热议问题