Search code examples
c++objectvectordestructordynamic-memory-allocation

Clean destruction of a vector of dynamically alocated objects


Is there another way of freeing the memory of the alocated objects, rather than iterating through the vector/list?

int main()
        {
            vector<Class*> v;
            v.push_back(new Class(2,2));
            v.push_back(new Class(65,65));
            v.push_back(new Class(45,23));
            for(Class* &it : v)
               delete it;
            return 0;
        }

Solution

  • yes there is. it is called smart pointers:

    std::vector<std::unique_ptr<Class>> v;
    v.push_back(std::make_unique<Class>(Class(2,5)));
    

    However if you don't have a reason to use dynamically allocated objects, prefer std::vector<Class>.

    Live