Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c++ - Deallocating objects stored in a vector?

I have a class that creates a vector of objects. In the deconstructor for this class I'm trying to deallocate the memory assigned to the objects. I'm trying to do this by just looping through the vector. So, if the vector is called maps I'm doing:

Building::~Building() {
    int i;
    for (i=0; i<maps.size(); i++) {
        delete[] &maps[i];
    }
}

When I run this the program segfaults while deallocating memory. I think what I'm doing is actually deleting the array storing the objects and not the objects themselves. Is this correct? If not any ideas as to what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It depends on how vector is defined.

If maps is a vector<myClass*> you delete each element with something similar to:

for ( i = 0; i < maps.size(); i++)
{
    delete maps[i];
}

If maps is a vector<myClass> I don't think you need to delete the individual elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...