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

前端 未结 7 939
日久生厌
日久生厌 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:47

    No.

    And you're doing it wrong. Return the vector instead so the lifetime works out:

    Write your own special Python memory vector class, something like (most crudely):

    template <typename T>
    class python_vector
    {
        T* buffer_;
    public:
        python_vector(size_t n, const T& value) : buffer_{new T(n)}
        {}
        // copy, assignment, operator[](), *etc*
        ~python_vector()
        {
            // DO NOTHING!
        }
    }
    
    python_vector<int> foo() {      
        python_vector<int> v(10,1);
        // process v
        return v;
    }
    
    int main()
    {
        python_vector<int> bar = foo();  // copy allusion will build only one python_vector here
        std::cout << bar[5] << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题