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
710 views
in Technique[技术] by (71.8m points)

c++ - Does std::vector.clear() do delete (free memory) on each element?

Consider this code:

#include <vector>

void Example()
{
    std::vector<TCHAR*> list;
    TCHAR* pLine = new TCHAR[20];
    list.push_back(pLine);
    list.clear();    // is delete called here?
    // is delete pLine; necessary?
}

Does list.clear() call delete on each element? I.e. do I have to free the memory before / after list.clear()?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

std::vector does call the destructor of every element it contains when clear() is called. In your particular case, it destroys the pointer but the objects remain.

Smart pointers are the right way to go, but be careful. auto_ptr cannot be used in std containers. boost::scoped_ptr can't either. boost::shared_ptr can, but it won't work in your case because you don't have a pointer to an object, you are actually using an array. So the solution to your problem is to use boost::shared_array.

But I suggest you use std::basic_string<TCHAR> instead, where you won't have to deal with memory management, while still getting the benefits of working with a string.


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

...